Simple Input and Output
C++ does not, as part of the language, define how data is written to a screen, nor how data is read into a program. This is usually done by "special variables" (objects) called input and output streams, cin and cout, and the insertion and extraction operators. These are defined in the header file called iostream. To be able to use these objects and operators you must include the file iostream at the top of your program by including the following line of code before the main body in your program.
#include <iostream>
Printing to the screen using output stream
A statement to print the value of a variable or a string of characters (set of characters enclosed by double quotes) to the screen begins with cout, followed by the insertion operator, (&«;) which is created by typing the ``less than'' character (<) twice. The data to be printed follows the insertion operator.
cout << text to be printed ;
cout << variable ;
cout << endl;
The symbol endl is called a stream manipulator and moves the cursor to a new line. It is an abbreviation for end of line.
Strings of characters and the values of variables can be printed on the same line by the repeated use of the insertion operator. For example (line 11 of the simple adder program):
int total = 12; cout << "The sum is " << total << endl;
prints out
The sum is 12
and then moves the cursor to a new line.
Input of data from the keyboard using input stream
The input stream object cin and the extraction operator, (&»;), are used for reading data from the keyboard and assigning it to variables.
cin >> variable ;
cin >> variable1 >> variable2 ;
Data typed at the keyboard followed by the return or enter key is assigned to the variable. The value of more than one variable can be entered by typing their values on the same line, separated by spaces and followed by a return, or on separate lines.
Back to top