Stream Input & Output Stream I/O Stream I/O
by overloading two functions with names operator<< and operator>>
#include <iostream>
struct point { int x; int y; }; std::ostream& operator << (std::ostream& os, point const& p) { return os << '(' << p.x << ',' << p.y << ')'; } std::istream& operator >> (std::istream& is, point& p) { return is >> p.x >> p.y; } int main () {
point p {1,2}; std::cout << p << '\n'; // prints (1,2) … std::cout << "enter two integers: ";
std::cin >> p; // reads 2 ints into p.x and p.y … std::cout << "p: " << p << '\n'; }
operator functions for stream input/output of objects of type T:
std::ostream& operator << (std::ostream& os, T const& x) { // write to stream … return os; }
std::istream& operator >> (std::istream& is, T& x) { // read from stream … return is; } Operators << and >> return a reference (to their stream parameter) to allow operator chaining:
cin >> x >> y; ⇔ operator>>( operator>>(cin, x), y) cout << x << y; ⇔ operator<<( operator<<(cout,x), y) There are no default stream operations in the standard library for containers like std::vector, because there are too many possible use cases:
- just print values … separated by what?
- format output as plain text / XML / …
- (de-)serialize container
- …
(Some) Standard Library Stream Types (Some) Standard Stream Types Stream Types
istream | input stream | reference istream& binds to any other kind of std:: input stream |
ostream | output stream | reference ostream& binds to any other kind of std:: output stream |
ifstream | input file stream | extracted data is read from a file |
ofstream | output file stream | inserted data is stored in a file |
ostringstream | output string stream | inserted data is stored in a string buffer |
istringstream | input string stream | extracted data is read from a string buffer |
Utilities
std::getline (istream&, string&, stopat='\n') reads until the next stopat character (default = until end of line)
string s; getline(cin, s); getline(cin, s, '\t'); getline(cin, s, 'a'); std::istream::ignore(n, c) - forwards stream by
ncharacters - until stop character
c
// skip next 8 characters cin.ignore(8);
// skip by max. 10 characters or until after '=' cin.ignore(10, '=');
// skip until after next newline character cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); #include <iostream>
#include <iomanip> int main () {
double d = 12.345678; double e = 2011; double f = 1e-10;
std::cout << d << e << '\n' << f << '\n'
<< std::setprecision(4) << d << '\n' << e << '\n' << f << '\n'
<< std::fixed << d << '\n' << e << '\n' << f << '\n'
<< std::scientific << d << '\n' << e << '\n' << f << '\n'
<< true <<' '<< false << '\n' << std::boolalpha << '\n' << true <<' '<< false << '\n'; }
header
12.345678 2011 1e-010
# of digits 12.35 2011 1e-010
fixed # of decimals 12.3457 2011.0000 1.0000e-010
scientific notation 1.2346e+001 2.0110e+003 1.0000e-010
1 0 booleans as string true false