Stream cheat sheet
Here is a brief summary of C++ streams.
Streams are the basic IO mechanism in C++.
There are four kinds of streams, shown here with the corresponding C
functions, and the include files you need for them.
Standard IO } ostream (printf)
iostream.h } istream (scanf)
File IO } ofstream (fprintf)
fstream.h } ifstream (fscanf)
char* IO } ostrstream (sprintf)
strstream.h } istrstream (sscanf)
string IO } ostringstream (no corresponding C function)
stringstream.h } istringstream (no corresponding C function)
"char* IO" means writing to (or reading from) a character array;
"string IO" means writing to (or reading from) a C++ string.
Standard IO streams
iostream.h
defines several global variables:
ostream cout; // standard output, buffered
ostream cerr; // standard error, unbuffered
ostream clog; // standard error, buffered
istream cin; // standard input
iomanip endl; // send a newline and flush
iomanip flush;// flush
Formatted output
Output is defined for all built-in types with the << operator, and
input with the >> operator. Think of the "arrows" as indicating the
flow of information.
#include <iostream.h>
main()
{
// you can print constants:
cout << "This is a test " << 666 << '\n' << 3.1415 << endl;
int a = 7;
char *s = "foo";
double d = 1.0/3;
// or variables:
cout << "a=" << a << " s=" << s << " d=" << d << endl;
cin >> a; // reads an int
cin >> s; // reads one *word*, not a line
cin >> d; // reads a double.
}
The input operators >>
skip whitespace before trying to read.
If input fails, the input stream turns on a bit called fail, which you
can test with a member function. After failing, an input stream will
ignore all requests to read until you tell it to clear itself.
cout << "Enter an integer: ";
int a;
cin >> a;
if (cin.fail())
{
cerr << "That wasn't an integer!" << endl;
cin.clear(); // reset the fail flag
// you would normally then loop and try again.
}
Unformatted input
istream
s provide operations to do unformatted input:
-
cin.getline (buf, len)
- reads a line (but no more than len chars) into buf, which should be
a char*.
-
cin.ignore (len, stopchar)
- skips over len characters, but stops if it sees a stopchar (eating the stopchar).
cin.get()
reads one character
getline (cin, str)
- This is a global function provided by the string class.
It reads a line into the string (dropping the newline).
for example, cin.ignore(MAXINT, '\n')
will read a line and throw it away.
Formatting operations
There are various operations on ostreams to do formatting:
cout.width (n) sets the width of the next field to n characters;
if the thing printed is less than n characters wide,
it will be padded.
cout.fill(ch) Do padding with character ch (by default, filling is
done with spaces)
cout.precision(n) Print n digits after the period for floats.
These functions return the old value; you can also call them with
no arguments to get the current value without changing it.
There are also manipulators that allow you to do these operations in
the middle of an output: setw for width, setfill for fill, setprecision
for precision:
cout << setfill ('0') << setw(2) << hour << ":" <<
setw(2) << minute;
All the attributes except for the width are "sticky"; they remain in force
until you explicitly change them. So it is good practice to restore
the stream to its original state:
char oldfill = cout.fill('0');
cout << setw(2) << hour << ":" << setw(2) << minute;
cout.fill (oldfill);
File streams
------------
File streams are used exactly like standard streams, except that you
specify a file when you create them:
// copy from one file to another
ifstream input ("file1");
ofstream output ("file2");
const int bufsize = 256;
char buf[bufsize];
while (input.getline (buf, bufsize))
output << buf << "\n";
When the file stream objects go out of scope, they close their files.
In-core formatting
------------------
If you want to write several values into a char array and then use that
array (e.g., as a filename or as the text for a window), you can use an
ostrstream:
ostrstream buffer;
buffer << "this is a test " << 666 << endl;
When you are done with your writing, you ask the strstream for its char*:
char *s = buffer.str();
This *freezes* the stream -- you are no longer allowed to write to it,
and *you* are now responsible for deleting the char*:
// use s...
delete [] s; // square brackets because it is an array of chars
If you want to read values from a string, you can use an istrstream:
char *s; // .... suppose s contains four integers separated by whitespace
istrstream parser (buf);
int a, b, c, d;
parser >> a >> b >> c >> d;
In-core formatting with strings
-------------------------------
stringstreams provide the same capabilities, but with the standard C++ type
string instead of a char*:
ostringstream buffer;
buffer << "this is a test " << 666 << endl;
string s = buffer.str();
This *freezes* the stream -- you are no longer allowed to write to it.
There is no deallocation to be done, though.
If you want to read values from a string, you can use an istringstream:
string s; // .... suppose s contains four integers separated by whitespace
istrstream parser (buf);
int a, b, c, d;
parser >> a >> b >> c >> d;
Jak Kirman