A stream is a sequence of characters that can be read from (input) or written to (output). Output streams use the insertion (<<) operator and input streams use the extraction (>>) operator. A stream can be connected to the console, a file or a string:
std::ostream#include <iostream>is the base class for output streams.std::istream#include <iostream>is the base class for input streams.std::iostream#include <iostream>derives from both.
The stream classes form an inheritance tree:
A function that takes a base class reference, such as std::ostream#include <iostream>&, accepts any stream derived from it:
void print(std::ostream#include <iostream>& os, int x) {
os << "x = " << x << "\n";
}
std::ofstream#include <fstream> file("out.txt");
std::ostringstream#include <sstream> ss;
print(std::cout#include <iostream>, 1); // Prints to the console.
print(file, 2); // Writes to out.txt.
print(ss, 3); // Writes to ss.A stream tracks whether an operation failed. When a read fails, the stream sets its fail flag and ignores further reads until the flag is cleared:
int x;
std::cin#include <iostream> >> x; // input: abc
std::cin#include <iostream>.fail(); // true
std::cin#include <iostream> >> x; // Does nothing.
std::cin#include <iostream>.clear(); // Clears the fail flag.
std::cin#include <iostream>.ignore(std::numeric_limits#include <limits><std::streamsize#include <ios>>::max(), '\n'); // Discards the bad input.The state can be checked with these methods:
good()is true when no error has occurred.fail()is true when an operation failed, such as reading a letter into anint.eof()is true when the end of the input has been reached.bad()is true when an unrecoverable error occurred, such as a failed disk read.
A stream converts to bool, which is the same as !fail(), so a read can be used directly as a condition:
int x;
if (std::cin#include <iostream> >> x) {
std::cout#include <iostream> << "Read " << x << "\n";
}iostream
The iostream header provides four standard streams:
std::cout#include <iostream>writes to standard output.std::cin#include <iostream>reads from standard input.std::cerr#include <iostream>writes errors to standard error, without buffering, so messages appear immediately.std::clog#include <iostream>writes logs to standard error, with buffering.
For example:
std::cout#include <iostream> << "Result: " << 42 << "\n";
std::cerr#include <iostream> << "Error: file not found.\n";
Dan