Monday 22 April 2013

Stream Library

The stream library is used for a common interface to input and output routines across
built-in types and your own types.
There are three streams available (cin, cout and cerr for standard input, standard
output and standard error streams respectively) and they are used in the following way:
#include <iostream.h>
int main()
{
int i = 45;
float f = 34.678;
cout << i; // print i
cout << f; // print f
cout << "\nEnter an integer: ";
// print a string
cin >> i; // read an integer
cout << i << f; // print i and f
return 0;
}
A range of manipulators exist to allow formatting of output. [ Remember that if all else
fails, printf is still there! ] Standard manipulators include:
oct use octal
dec use decimal
hex use hexadecimal
endl newline ('\n')
ends end of string ('\0')
flush flush stream
ws skip white space
setbase(int) use base specified
setfill(int) set fill character
setprecision(int) set number of digits printed
setw(int) set field width
Declarations for these manipulators are in iomanip.h. For example:
cout << setw(8) << 1 << setw(8) << setfill('#') << 2
<< endl;
cout << hex << 123 << ' ' << oct << 123 << endl;
prints:
1#######2
7b 173
The setw manipulator applies only to the next numeric or string value printed, hence the
need for two calls to setw above. The setfill manipulator modifies the state of the
stream, and will apply to all subsequent output on that stream.

No comments:

Post a Comment