Brief Introduction to C++ Input/Output

An introduction to using the standard cout and cin output/input streams.

  1. Basic Input and Output in C++
    1. The iostream Library
    2. The std Namespace
    3. Input/Output Streams and Insertion/Extraction Operators
  2. How to use cin and cout
    1. Using cout
      1. Writing Multiple Datums to cout
      2. Output Flags
    2. Using cin
      1. Reading Multiple Inputs From cin
      2. Type Mismatch Problems with cin

0. Goals

This introduction is intended to give a brief, yet usable, introduction to using the C++ cin and cout streams. It is not an exhaustive overview of what they are and how they work.

The goal of this document is simply to provide enough information so that students begining to learn C++ can use cin and cout effectively.

This introduction can be read and worked through (on the computer, testing each example!) in roughly 30 minutes by introductory students.

1. Basic Input and Output in C++

With C++, students typically start writing console (or terminal) applications, where all input and output is done through a text-only interface, rather than a graphical user interface (GUI).

When a program has a GUI, a user interacts with the program via menus, buttons, text inputs, and other graphical elements, utilizing both the keyboard and the mouse.

Programs with a text-only interface, however, are interacted with using only the keyboard. For such interaction to take place, we need some way of both writing text (and other forms of data) to the console (output), as well as some way of reading text (and other forms of data) from the console (input), which is done via the keyboard.

1.1 The iostream Library

In C++, such interaction can be accomplished using the standard iostream library, which can be included in any program by including the line
   #include <iostream>
at the top of your program.

Note that since iostream is a standard library, it is provided with every C++ distribution (i.e. this library can be used regardless of what operating system and architecture one is compiling their C++ programs on).

When this library is included in any program, a standard set of objects become available to the program. Two such objects are called cin and cout, which are input and output streams, respectively.

1.2 The std Namespace

Sadly, the following must be mentioned, but there is no need to go into too much detail for the purpose of this document. If you don't know what a namespace is, don't worry.

All objects defined in any standard C++ library are defined within the standard "std" namespace. All this means is that all of the objects "imported" from these standard libraries include the prefix std:: in their name. As such, cin and cout are really named "std::cin" and "std::cout".

If one wishes to avoid using these prefixes (which can be cumbersome), then one can instruct the compiler to "import" all of the objects from the std namespace into the program's default namespace by doing the following...
   #include <iostream>
   using namespace std;
With the line "using namespace std;" added to any program, cin and cout can be used without the std:: prefix.

If one did not want to import all of the objects defined in iostream into the default namespace (there are many, many more objects defined in iostream), then one could import only specific objects, such as cin and cout, by instead doing the following...
   #include <iostream>
   using std::cin;
   using std::cout;
Again, once the above lines are added, cin and cout can be used without the std:: prefix.

1.3 Input/Output Streams and Insertion/Extraction Operators

As stated above, cin and cout are input and output streams, and are used to both read data from the console (via the keyboard) and output data to the console. We say that when a programs runs, cin is bound to the keyboard and cout is bound to the console window.

What this means is that anytime a programmer wishes to capture input from the keyboard, such can be accomplished by reading data from the cin stream. Similarly, anytime a programmer wishes to write data to the console window, such can be accomplished by writing data to the cout stream.

Anytime the user types text into the keyboard, the typed input is loaded into the cin stream which can then be read from using the stream extraction operator ">>".

Similarly, whenever the programmer wants to writes data to the cout stream, that data appears in the console window. Writing data to the cout stream is accomplished using the stream insertion operator "<<".

2. How to use cin and cout

What follows below is how to use both cin and cout. If you've quickly scanned to this part of the document, please take 5 minutes and read the first section above!

2.1 Using cout

To write data to the cout stream (i.e. to output data to the console), simply use the stream insertion operator (<<) to "put" the data into the output stream. The general format is...
   cout << DATA;
...where DATA is any type of data (static values, variables, or expressions). Note that the arrows (i.e. the stream insertion operator "<<") is pointing towards cout, indicating that DATA will be "put into" cout (and thus appear in the console window).

In the following example, the static string "Hello World!" is inserted to the cout stream, and thus output to the console.
   cout << "Hello World!";
When run, the code above would produce the following output in the console
   Hello World!
As stated above, the data we insert into cout could also be variables or expressions. When variables and expressions are inserted into the cout stream, their resulting values are what is finally output.

For example, the following code...
   int x = 42;
   float y = 12.34;
   char z = 'A';
   cout << "x = ";
   cout << x;
   cout << endl;
   cout << "y = ";
   cout << y;
   cout << endl;
   cout << "z = ";
   cout << z;
   cout << endl;
   cout << "(x + y) = ";
   cout << (x + y);
   cout << endl;
   cout << "(x / 2) = ";
   cout << (x / 2);
   cout << endl;
   cout << "(7 + 3) = ";
   cout << (7 + 3);
   cout << endl;
   cout << "(2 < 3) = ";
   cout << (2 < 3);
   cout << endl;
...would produce the following output in the console when run
   x = 42
   y = 12.34
   z = A
   (x + y) = 54.34
   (x / 2) = 21
   (7 + 3) = 10
   (2 < 3) = true
Note that the keyword endl, when output, produces a new line in the text. This keyword is included from the iostream library, and as such, is within the std namespace. Thus, if you intend to use endl as above, you will have to either include using namespace std; at the top of your file or using std::endl;.

2.1.1 Writing Multiple Datums to cout

Multiple objects may be inserted into the cout stream in a single statement by simply using multiple instances of the stream insertion operator (once before each object). The general format for this is...
   cout << DATUM1 << DATUM2 << DATUM3 ...;
...where each of the DATUMs is preceeded by the stream insertion operator "<<". Note also that each datum may be of a different type (static value, variable, or expression), as is illustrated in the next example.

The following program outputs a mixing of text and variables in a single cout statement. Note again that the "\n" character, when output, will produce a new line. Note also that the statement can be broken onto multiple lines to make it more readable, but a semi-colon is only required at the end of the statement.
   int x = 42;
   char y = 'a';
   float z = 7.2;

   cout << "x = " << x << endl
        << "y = " << y << endl
        << "z = " << z << endl;
When run, the above program would produce the following output
   x = 42
   y = a
   z = 7.2

2.1.2 Output Flags

2.2 Using cin

When reading data from the cin stream (i.e. when reading data from the keyboard), we must first have some place to store that data. To do this, we must first have a variable, which is of the same type as the data being read...more on that point in a minute. The general format is...
   cin >> VARIABLE;
...where VARIABLE is the name of the variable that the input from the keyboard will be stored. Note that the arrows here (i.e. the stream extraction operator ">>") are pointing towards the variable, indicating that data will be "put into" the variable.

Suppose we wanted to read a number from the keyboard. We first create a variable of some numeric type (say int), and then use the stream extraction operator (>>) to extract that input into the variable.
   int x;
   cin >> x;
When the above code executes, the program will pause at the use of cin, waiting for the user to type something on the keyboard and hit the enter key. After that, whatever number the user entered will be stored in the variable x.

To see how this would play out, consider the following program...
   int x;
   cout << "Enter a number: ";
   cin >> x;
   cout << "You just entered the number '" << x << "'";
When run, such code would look like the following in the console. Note that all output from the program is in white, all input from the user is in red, and the pressing of the "Enter" key is represented by .
   Enter a number: 42 
   You just entered the number '42'

2.2.1 Reading Multiple Inputs from cin

Similar to how cout can output multiple objects, cin can also be used to read multiple objects from the keyboard, simply by including multiple variable names after the cin statement, each seperated by a stream extraction operator (>>). The general format for this is...
   cin >> VARIABLE1 >> VARIABLE2 >> VARIABLE3 ...;
...where each of the VARIABLEs is preceeded by the stream extraction operator ">>". Note that each variable may also be of a different type, as is illustrated in the next example.

The following program reads three things from the keyboard: a whole number (integer), a character, and then a decimal (floating point) number.
   int x;
   char y;
   float z;

   cout << "Enter a whole number, then a character, and then a floating-point number: ";
   cin >> x >> y >> z;

   cout << "You just entered the whole number '" << x << "', "
        << "the character '" << y << "', "
        << "and the floating point number '" << z << "'";
When the program is run, the user can enter the multiple inputs by seperating each by spaces, tabs, or even new-lines. For example, the user may do the following...
   Enter a whole number, then a character, and then a floating point number: 42  a  7.2 
   You just entered the whole number '42', the character 'a', and the floating point number '7.2'
...or the user may hit enter after each input, as in the following...
   Enter a whole number, then a character, and then a floating point number: 42
   a
   7.2
   You just entered the whole number '42', the character 'a', and the floating point number '7.2'
Either fashion will work. It's important to note, however, that the program will remain waiting for input until all inputs have been read, and a final press of the "Enter" key has been made.

2.2.2 Type Mismatch Problems with cin

Notice that one can read any type of variable from the keyboard (an integer, a character, or a floating point number) and the C++ cin stream object automatically converts the input into the appropriate type and places the value "into" the variable. This is a major convienance to any programmer.

This conversion, however, isn't always possible, and may lead to unexpected run-time problems if a conversion is not possible.

For example, if a program is instructed to read an integer from the keyboard like so...
   int x;
   cin >> x;
...but the user inputs something other than an integer, such as a long string of text, there is no way for cin to convert this value into an integer in any valid fashion. Worse, cin will try to do this conversion anyway. When this happens, a program may "go crazy" and output pages and pages of text, never halting. The user will most likely have to forcefully quit the program.

There are ways of validating what the user enters, and handling such erroneous inputs from the user in a more appropriate manner, but such techniques are beyond the scope of this document.

For this class, you may safely assume that the user will always input a value that cin can correctly convert to the appropriate type.
Of course, this means you must let the user know what type of data the user should input!


Ryan Flannery (ryan.flannery@gmail.com), 20 June 2007