The Standard Input Stream

In addition to printing messages, you may want to read data from the keyboard. C++ includes its own version of standard input in the form of cin. The next example shows you how to use cin to read an integer from the keyboard.

#include <iostream.h>

void main()

{

int amount;

cout << "Enter an amount...\n";

cin >> amount;

cout << "The amount you entered was " << amount;

}

This example prompts you to enter an amount. Then cin sends the value that you enter to the variable amount. The next statement displays the amount using cout to demonstrate that the cin operation worked.

You can use cin to read other data types as well. The next example shows how to read a string from the keyboard.

#include <iostream.h>

void main()

{

char name[20];

cout << "Enter a name...\n";

cin >> name;

cout << "The name you entered was " << name;

}

The approach shown in this example has a serious flaw. The character array is only 20 characters long. If you type too many characters, the stack overflows and peculiar things happen. The get function solves this problem. It is explained in Chapter 18, “The Fundamentals of iostream Programming” in the Class Libraries User's Guide. For now, the examples assume that you will not type more characters than a string can accept.

Note:

Recall that printf and scanf are not part of the C language proper, but are functions defined in the run-time library. Similarly, the cin and cout streams are not part of the C++ language. Instead, they are defined in the stream library, which is why you must include IOSTREAM.H in order to use them. Furthermore, the meaning of the << and >> operators depend on the context in which they are used. They can display or read data only when used with cout and cin.