You are on page 1of 20

I/O Streams and Standard I/O Devices

A program performs three basic operations: it gets data, it manipulates the data, and it outputs the results

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

Input stream: A sequence of characters from an input device to the computer.


Output stream: A sequence of characters from the computer to an output device.

To receive data from the keyboard and send output to the screen, every C++ program must use the header file
iostream. #include <iostream>

cin and the Extraction Operator >>


Consider the following C++ statement:
double payRate;
cin >> payRate;
When the computer executes this statement, it inputs the next number typed on the keyboard and stores this number in
payRate. Therefore, if the user types 15.50, the value stored in payRate is 15.50.
The syntax of an input statement using cin and the extraction operator >> is:

cin >> variable >> variable...;


As you can see in the preceding syntax, a single input statement can read more than one data item by using the
operator >> several times
For example, you can read both payRate and hoursWorked via a single input statement by using the following
code:
cin >> payRate >> hoursWorked;
For example, suppose that payRate and hoursWorked are double variables. Consider the following input statement:
cin >> payRate >> hoursWorked;
Whether the input is:

15.50 48.30 or: 15.50 48.30 or: 15.50


48.30
the preceding input statement would store 15.50 in payRate and 48.30 in hoursWorked.
Note: that the first input is separated by a blank, the second input is separated by a tab, and the third input is
separated by a line.

Next, consider the input 25 and the statement: cin >> a;


where a is a variable of some simple data type. If a is of the data type char, only the single character 2 is stored in a.
If a is of the data type int, 25 is stored in a. If a is of the data type double, the input 25 is converted to the decimal
number 25.0.
Suppose you have the following variable
declarations:
int a, b;
double z;
char ch;

The following statements show how the extraction


operator >> works.
Entering a char value
into an int or double
variable causes
serious errors,
called input failure
Using Predefined Functions in a Program
C++ comes with a wealth of functions, called predefined functions, that are already written.

The predefined functions are organized as a collection of libraries ,called header files. A particular header file
may contain several functions. Therefore, to use a particular function, you need to know the name of the
function and a few other things, which are described shortly.

The program in the following example illustrates how to use predefined functions in a program. More specifically, we
use some math functions, from the header file cmath, and the string function length, from the header file string. Note
that the function length determines the length of a string.
cin and the get Function
As you have seen, the extraction operator skips all leading whitespace characters when scanning for the next input
value. Consider the variable declarations:
char ch1, ch2;
int num;
and the input:
A 25
Now consider the following statement:
cin >> ch1 >> ch2 >> num;
When the computer executes this statement, 'A' is stored in ch1, the blank is skipped by the extraction operator >>,
the character '2' is stored in ch2, and 5 is stored in num. However, what if you intended to store 'A' in ch1, the blank
in ch2, and 25 in num? It is clear that you cannot use the extraction operator >> to input this data.

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.

The syntax of cin, together with the get function to read a character, follows:
cin.get(varChar);
Now consider the following input again:
A 25
To store 'A' in ch1, the blank in ch2, and 25 in num, you can effectively use the get function as follows:
cin.get(ch1);
cin.get(ch2);
cin >> num;
The preceding form of the get function reads values of only the char data type.
cin and the ignore Function

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

cin.ignore(intExp, chExp);

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 intExp yields a value of, 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. To be specific, consider the following
statement:
cin.ignore(100, '\n');
Consider the declaration:
int a, b;
and the input:
25 67 89 43 72
12 78 34
Now consider the following statements:
cin >> a;
cin.ignore(100, '\n');
cin >> b;
The first statement, cin >> a;, stores 25 in a. The second statement, cin.ignore(100, '\n');, discards all of the remaining
numbers in the first line. The third statement, cin >> b;, stores 12 (from the next line) in b.
When the function ignore is used without any arguments, then it only skips the very next character. For example, the
following statement will skip the very next character:
cin.ignore();
Output and Formatting Output
Other than writing efficient programs, generating the desired output is one of a programmer’s highest priorities.
there is a lot more to output than just displaying results. Sometimes, floating point numbers must be output in a
specific way. For example, a paycheck must be printed to two decimal places, whereas the results of a scientific
experiment might require the output of floating-point numbers to six, seven, or perhaps even ten decimal places.
Also, you might like to align the numbers in specific columns or fill the empty space between strings and numbers
with a character other than the blank.

Recall that the syntax of cout when used together with the insertion operator << is:
cout << expression or manipulator << expression or manipulator...;
Here, expression is evaluated, its value is printed, and manipulator is used to format the output.

setprecision Manipulator
You use the manipulator setprecision to control the output of floating-point numbers. The general syntax of the
setprecision manipulator is: setprecision(n) where n is the number of decimal places.

for example
cout << setprecision(2); formats the output of decimal numbers to two decimal places

To use the manipulator setprecision, the program must include the header file iomanip. Thus, the following include
statement is required: #include <iomanip>
fixed Manipulator
To further control the output of floating-point numbers, you can use other manipulators. To output floating-point
numbers in a fixed decimal format, you use the manipulator fixed.

The following statement sets the output of floating-point numbers in a fixed decimal format on the standard output
device:
cout << fixed;
After the preceding statement executes, all floating-point numbers are displayed in the fixed decimal format until the
manipulator fixed is disabled.
You can disable the manipulator fixed by using the stream member function unsetf.

After the manipulator fixed is disabled, the output of the floating-point numbers returns to their default settings.

The manipulator scientific is used to output floating-point numbers in scientific format.


#include <iostream> cout << "hours = " << hours << ", rate = " << rate
using namespace std; << ", pay = " << hours * rate
int main() << ", tolerance = " << tolerance << endl << endl;
{ cout << fixed;
double hours = 35.45; cout << "Fixed decimal notation: " << endl;
double rate = 15.00; cout << "hours = " << hours << ", rate = " << rate
double tolerance = 0.01000; << ", pay = " << hours * rate
cout << "hours = " << hours << ", rate = " << rate << ", tolerance = " << tolerance << endl << endl;
<< ", pay = " << hours * rate return 0;
<< ", tolerance = " << tolerance << endl << endl; }
cout << scientific;
cout << "Scientific notation: " << endl;

Sample Run:
hours = 35.45, rate = 15, pay = 531.75, tolerance = 0.01

Scientific notation:
hours = 3.545000e+001, rate = 1.500000e+001, pay = 5.317500e+002, tolerance = 1.000000e-002

Fixed decimal notation:


hours = 35.450000, rate = 15.000000, pay = 531.750000, tolerance = 0.010000
showpoint Manipulator
Suppose that the decimal part of a decimal number is zero. In this case, when you instruct the computer to output the
decimal number in a fixed decimal format, the output may not show the decimal point and the decimal part. To force
the output to show the decimal point and trailing zeros, you use the manipulator showpoint.

cout << showpoint; //sets the output of decimal numbers with a decimal point and trailing zeros.
cout << fixed << showpoint; // sets the output of a floating-point number in a fixed decimal format with the decimal point and
trailing zeros
setw
The manipulator setw is used to output the value of an expression in a specific number of columns. The value of the
expression can be either a string or a number. The expression setw(n) outputs the value of the next expression in n
columns. The output is right justified. Thus, if you specify the number of columns to be 8, for example, and the output
requires only four 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.
Int x;
cout << setw(5) << x << endl; // outputs the value of x in five columns on the standard output device

To use the manipulator setw, the program must include the header file iomanip. Thus, the following include statement
is equired:
#include <iomanip>

setw controls the output of only the next expression.


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 to the left are filled with spaces.
The output stream variables can use the manipulator setfill to fill the unused columns with a character other than a
space.
cout << setfill('#'); // sets the fill character to '#' on the standard output device.
To use the manipulator setfill, the program must include the header file iomanip.
left and right Manipulators
Recall that if the number of columns specified in the setw manipulator exceeds the number of columns
required by the next expression, the default output is right-justified. Sometimes, you might want the output
to be left-justified. To left-justify the output, you use the manipulator left.

cout << left; sets the output to be left-justified on the standard output device:
cout << right; sets the output to be right-justified on the standard output device:
Input/Output and the string Type
You can use an input stream variable, such as cin, and the extraction operator >> to read a string into a variable of
the data type string. For example, if the input is the string "Shelly", the following code stores this input into the
string variable name:
string name; //variable declaration
cin >> name; //input statement

Recall that the extraction operator skips any leading whitespace characters and that reading stops at a whitespace
character. As a consequence, you cannot use the extraction operator to read strings that contain blanks. For example,
suppose that the variable name is defined as noted above. If the input is:
Alice Wonderland
then after the statement:
cin >> name;
executes, the value of the variable name is "Alice".
To read a string containing blanks, you can use the function getline.

The syntax to use the function getline is:


getline(istreamVar, strVar);

where istreamVar is an input stream variable and strVar is a string variable. The reading is delimited by the newline
character '\n'.
Consider the following statement:
string myString;
If the input is 29 characters:
bbbbHello there. How are you?
where b represents a blank, after the statement:
getline(cin, myString);
the value of myString is:
myString = " Hello there. How are you?“
All 29 characters, including the first four blanks, are stored into myString.

You might also like