Department of Engineering

IT Services

Text input and output

To make use of the input and output facilities described here, the header file for the type iostream and associated operators must be included by using the compiler directive:

#include <iostream>
using namespace std;

The input stream cin and the extraction operator (>>) are used for reading data from the keyboard and assigning it to variables. cin and cout (see below) are pre-defined variables of type iostream. The >> and << operators, when associated with cin and cout, are examples of user-defined operators, as discussed in section 6.

cin >> v;

Data typed at the keyboard followed by the return or enter key is assigned to the variable v.

cin >> v1 >> v2;

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.

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 (<<). The data to be printed follows the insertion operator.

cout << "text to be printed";
cout << v;
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.

   int total = 12;
   cout << "The sum is " << total << endl;

prints out

   The sum is 12

and then moves the cursor to a new line.