C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

Learn About Input and Output

By David Bolton, About.com

1 of 8

A New Way to Output

C++ retains very high backwards compatibility with C, so <stdio.h> can be included to give you access to the printf() function for output. However the I/O provided by C++ is significantly more powerful and more importantly type safe. You can still also use scanf() for input but the type safety features that C++ provides means that your applications will be more robust if you use C++.

In the previous lesson, this was touched on with an example that used cout. Here we'll go into a bit more depth starting with output first as it tends to be more used than input.

The iostream class provides access to the objects and methods you need for both output and input. Think of i/o in terms of streams of bytes- either going from your application to a file, the screen or a printer - that's output, or from the keyboard - that's input.

Output with cout

If you know C, you may know that << is used to shift bits to the left. Eg 3 << 3 is 24. Eg left shift doubles the value so 3 left shifts multiplies it by 8.

In C++, << has been overloaded in the ostream class so that int, float, and strings types (and their variants- eg doubles) are all supported. This is how you do text output, by stringing together multiple items between <<.

cout << "Some Text" << intvalue << floatdouble << endl;

This peculiar syntax is possible because each of the << is actually a function call which returns a reference to an ostream object. So a line like the above is actually like this

cout.<<("some text").cout.<<( intvalue ).cout.<<(floatdouble).cout.<<(endl) ;
The C function printf was able to format output using Format Specifiers such as %d. In C++ cout can also format output but uses a different way of doing it.

On the next page - Formatting with Cout.

Explore C / C++ / C#

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

C / C++ / C#

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. C++ Tutorial - Learn About Input and Output

©2009 About.com, a part of The New York Times Company.

All rights reserved.