BASIC INPUT/OUTPUT OPERATIONS

Here, you will only look at enough of C++ input and output to get you through learning about C++. It’s not that it’s difficult — quite the opposite, in fact — but for Windows programming, you won’t need it at all. C++ input/output incorporates the notion of a data stream. You can insert data into an output stream or extract data from an input stream. You have already seen that the standard output stream to the command line on the screen is referred to as cout. The complementary input stream from the keyboard is referred to as cin. Of course, both stream names are defined within the std namespace.

Input from the Keyboard

You obtain input from the keyboard through the standard input stream, cin, using the extraction operator for a stream, >>. To read two integer values from the keyboard into integer variables num1 and num2, you can write this statement:

std::cin >> num1 >> num2;

The extraction operator, >>, “points” in the direction that data flows — in this case, from cin to each of the two variables in turn. Any leading whitespace is skipped, and the first integer value you key in is read into num1. This is because the input statement executes from left to right. Any whitespace following num1 is ignored, and the second integer value that you enter is read into num2. There has to be some whitespace between successive values, though, so that they can be differentiated. The stream input operation ends when you press the Enter key, and execution then continues ...

Get Ivor Horton's Beginning Visual C++ 2012 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.