Back to CEO's Home Page

Input/Output

Reference: C++ Programming: From Problem Analysis to Program Design, 2nd Ed. by D. S. Malik

Charles E. Oyibo

I/O Streams and Standard I/O Devices

A program performs three basic operations:

In C++, I/O is a sequence of bytes called stream of bytes, from the source to the destination. The bytes are usually characters, unless the program requires other types of information such as graphical information or digital speech. Hence, a stream is a sequence of characters from the source to the destination. There are two types of streams:

Recall that the standard input device is the keyboard and the standard output device is the screen.

To receive data from the keyboard and send output to the screen, every C++ program must include the header file iostream, which includes, among other things, the definitions of two data types, istream (input stream) and ostream (output stream). The header file also contains two variable declarations, one for cin (common output), and one for cout (common output).

To use cin and cout, every C++ program must use the preprocessor directive:

#include <iostream>

We follow the #include <iostream> preprocessor directive with using namespace std; so that we do not have to refer to the cin and cout identifiers as std::cin and std::cout throughout the program. We will explore the meaning of using namespace std; later on.

A stream variable is either an input stream variable (variable of the type istream) or an output stream variable (variable of the type ostream).

cin and the Extraction Operator >>

The extraction operator >> is binary and takes two operands. The left side operand must be an input stream variable such as cin. Because the purpose of an input statement is to read and store values in a memory location, and because only variables refer to memory location, the right-side operand is a variable.

The extraction operator >> is defined only for putting data into variables of simple data types (int, float, double, char, bool). However C++ allows the programmer to extend the definition of the extraction operator >> so that data can also be put into other types of variable by using the input statement.

The syntax of an input statement using cin and the extraction operator >> is:

cin >> variable >> variable...;

Note from the preceding syntax that a single input statement can read more than one data item by using the operator >> several times. Every occurence of >> extracts the next data item from the input stream, skipping all whitespace characters (blanks, tabs, and the newline character).

Note that if the input stream has more data items than required by the program by the time the program terminates, the values that are left (in the input stream) are discarded.

It is also crucial for the data that is entered for processing to correspond to the data types of the variables in the input statement.

Capturing whitespaces

There are situations where it is desireable to store and process whitespace characters. Next we discuss how to input data into a program using the input functions such as get, ignore, putback, and peek. These functions are associated with the data type istream and are called istream member functions.

Using Predefined Functions in a Program

Recall that predefined functions are organized as a collection of libraries, called header files. A particular header file may contain several functions.

An example of a function is the power function, pow, can be used to calculate xy thus: pow(x, y). The numbers x and y that we use in the function pow are called the arguments or parameters of the function pow. An expression such as pow(x, y) is called a function call, which causes the code attached to the function pow to execute and, in this case, computes xy. The header file cmath contains the specification of the function pow.

cin and the get Function

As noted earlier, it is sometimes desireable to process the entire unit of input, including whitespace characters. Because the extraction operator >> skips whitespace characters, we would not be able to input whitespaces using only the extraction operator.

Enter the stream function get. The variable cin can access the stream function get, which is used to read character data. The get function inputs the very next character, including whitespace characters, from the input stream and stores it in the memory location indicated by its argument. The function get comes in many forms, but we will concern ourselves with the one that is used to read a character.

The general syntax to use the get function to read a character is:

istreamVar.get(varChar);

where istreamVar is an input stream variable such as cin.

In the istreamVar.get statement, varChar, a char variable, is called the argument or parameter of the function. The effect of the preceding statement would be to store the next input character in the variable varChar.

Example:

char ch1, ch2;

cin >> ch1; //reads the first character input, skips whitespaces
cin.get(ch2); //reads the next character input, even if it is a whitespace

To conclude, we can use the get function to read data only into the char data type.

cin and ignore Function

When we want to process only partial data (say, within a line), we can use the stream function ignore to discard a portion of the input. The general syntax to use the function ignore is:

istreamVar.ignore(intExt, chExp);

where, again, istreamVar is an input stream variable such as cin.

Here intExp is an integer expression yielding an integer value, and chExp is a char expression yielding a char value. In fact, the value of the expression intExp specifies the maximum number of characters to be ignored in a line.

Suppose the intExp yields a value, say 100. This statement says to ignore the next 100 characters, or ignore the input until it encounters the character specified by chExp, whichever comes first.

Example:

cin.ignore(100, '\n');

When this statement executes, it ignores either the next 100 characters or all characters until the newline character is found, whichever comes first.

putback and peek Functions

...

Dot Notation Between I/O Stream Variables and I/O Functions: A Precaution

It is important to use the functions previously covered (get, ignore, peek, and putback) in the exact syntax prescribed by C++. To use the get statement, for example, we must type

cin.get(ch);

Omitting the dot -- the period between cin and get -- for example, will result in a syntax error.

Called the dot notation, the dot separates the input stream variable name from the member, or function, name. In fact, in C++, the dot is an operator called the member access operator.

C++'s special name for the data types istream and ostream is classes. The variables cin and cout also have special names, called objects. Hence, cin is called in input stream object, and cout is called an output stream object. In fact, stream variables are called stream objects.

Input Failure

A program that is syntactically correct might produce incorrect results. A program might attempt to read invalid data, or might try to put a letter into an int variable, or say the programmer accidentally typed + in place of *... All these would result in a fail state resulting from the input failure.

Once an input stream enters the fail state, all futher I/O statements using that stream are ignored. However, the program continues to execute with whatever values are stored in variables and produce incorrect results

clear Function

As said previously, when an input stream enters the fail state, the system ignores all further I/O using that stream. We can use the clear function clear to restore the input stream to a working state. The syntax is:

istreamVar.clear();

istreamVar is an input stream, such as cin.

After using the function clear to return the input stream to a working state, we still need to clear the rest of the garbage from the input stream. This is accomplished using the function ignore.

Output and Formatting Output

Sometimes floating-point numbers must be output in a specific way. Or might like to align the numbers in specific columns or fill the empty spaces between strings and numbers with characters other than blank spaces (e.g. in preparing the table of contents of a book, the space between the section heading and the page number might need to be filled with dots). Recall the syntax of cout when used together with the insertion operator <<:

cout << expression or manipulator << expression or manipulator...;

Here, the expression is evaluated, its value is printed, and manipulator is used to format the output. We have use the endl manipulator (to move the insertion point to the beginning of the next line) thus far. We will look at the setprecision, fixed, showpoint, and flush manipulators in the next couple of sections.

setprecision Manipulator

We use the manipulator setprecision to control the output of floating-point numbers. (Recall that the default of floating-point numbers is scientific notation). The general syntax of the setprecision manipulator is

setprecision(n)

where n is the number of decimal places.

We use the setprecision manipulator with cout and the extraction operator. For example, the statement

cout << setprecision(2);

formats the output of decimal number to two decimal places until a similar subsequent statement changes the precision. To use the manipulator setprecision, we must include the header file iomanip using the following include statement

#include <iomanip>

fixed manipulator

To show the computer to show the decimal point and trailing zeros, we use the manipulator showpoint:

cout << showpoint;

Using the fixed and showpoints manipulators together, we can set the output of floating point numbers in a fixed decimal format with decimal point and trailing zeros on the standard output device.

cout << fixed << showpoint;

setw

The manipulator setw is used to output the value of an expression in specific columns, the value of the expression being either a string or a number. The statement setw(n) output the value of the next expression in n column. The output is right-justified. Hence, if we specify the number of columns to be 8, and the output requires only 4 columns, the first four columns are left blank. Furthermore, if the number of columns specified is less than the number of columns required by the output, the output automatically expands to the required number of columns; the output is not truncated.

E.g.

cout << setw(5) << x << endl;

outputs the value of x in five columns on the standard output device.

flush Manipulator

Both the manipulator endl and the newline escape sequence '\n' position the insertion point at the beginning of the next line of the output device. The manipulator endl, however, has another use.

When a program sends output to an output device, the output first goes to the buffer in the computer. Whenever the buffer becomes full, the output is sent to the output device. However, as soon as the manipulator endl is encountered, the output from the buffer is sent to the output device immediately, even if the buffer is not full. Therefore, the manipulator endl positions the insertion point at the beginning of the next line on an output device and helps clear the buffer.

It is however possible for the entire output not to have been sent to the output device because the buffer was not full at the time that the program terminated. In C++, we can use the manipulator flush to clear the buffer, even if the buffer is not full. In contract to the manipulator endl, the manipulator flush does not move the insertion point to the beginning of the next line.

The syntax to use the flush function is

ostreamVar << flush;

where ostreamVar is an output stream, such as cout. E.g. the following statement sends the output from the buffer to the standard output device (which positioning the insertion point at the beginning of the next line).

cout << flush;

endl vs flush

Consider three separate lines of code

cout << "Please enter an integer: " ; //1

cout << "Please enter an integer: " << endl; //2

cout << "Please enter an integer: " << flush; //3

The output of the statement of Line 1 first goes to the buffer and might not be displayed if the buffer is not full, in which case the user might have no idea what to do next.

The output of the statement of Line 2 is also sent to the buffer, but is immediately sent to the output device. However, the insertion point is positioned at the beginning of the next line, which in this situation looks unappealing.

The output of the statement of Line 3 is also sent to the buffer, and also immediately sent to the output device, but the insertion point stays positioned after the colon.

Additional Output Formatting Tools

setfill Manipulator

Recall that, in the manipulator setw, if the number of columns specified exceeds the number of columns required by the expression, the output of the expression is right-justified and the unused columns

 

left and right Manipulators

 

 

Input/Output and the string Type

 

 

File Input/Output

 

 

Top of page

Contact Information

Page Last Updated: Saturday February 12, 2005 10:21 AM