Wednesday 25 July 2012

iostream Library

<iostream>

The header <iostream> defines global object cin of type istream, and global objects cout, cerr, clog of type ostream. cin represents standard input, normally the keyboard, unless redirected to a file or piped on the command line. cout represents standard output, which is normally the screen unless redirected or piped. Writing to cerr or clog both write to the screen even if output is redirected. The difference is that writing a newline ('\n') flushes any buffered output to cerr but not to cout or clog.

In the following, in is an istream (cin), out is an ostream (cout, cerr, clog), i is int, c is char, and cp is char*.
in >> x; // Read 1 word to numeric, string, or char* x, return in
in.get(); // Read 1 char (0-255) or EOF (-1) as an int
in.get(c); // Read 1 char into c, return in
in.unget(); // Put back last char read, return in
in.getline(cp, i); // Read up to i chars into char cp[i] or until '\n', return in
in.getline(cp, i, c); // Read to c instead of '\n', return in
getline(in, s); // Read up to '\n' into string s, return in
in.good(); // true if no error or EOF
bool(in); // in.good();
in.bad(); // true if unexpected char in formatted input
in.clear(); // Allow more input after bad, or throw an ios::failure
in.eof(); // true if end of file
in.fail(); // true if system input error

out << x; // Formatted output, redirected with >
out << endl; // Print '\n' and flush

Input with >> reads a contiguous sequence of non-whitespace characters. If x is numeric and the next word contains invalid characters (such as "1.5" or "foo" for an int), then the first offending character remains unread, in.bad() is set, and no further input can occur until in.clear() is called. Input into a char* array is not bounds checked. Input returns the istream to allow chaining, and has a conversion to bool to test for success. Output also returns the ostream to allow chaining.
// Read and print pairs of strings and ints until something goes wrong
// Input: hi 3 there 5 this is 1 test
// Output: hi 3
there 5

string s; int i;
while (cin >> s >> i)
cout << s << " " << i << endl;
cin.clear();

The get() methods read one character including whitespace. The various getline() functions read up through the next newline character and discard the newline. The methods good(), bad(), eof(), fail(), clear(), and implicit conversion to bool are available in ostream, just as in istream, but are seldom used.

No comments:

Post a Comment