Stream Input & OutputStream I/OStream I/O
by overloading two functions with names
operator<<
and operator>>
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;
}
point p {1,2};
cout << p << '\n'; // prints (1,2)
…
cin >> p; // reads 2 ints into p.x and p.y
…
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
n
characters - 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 <iomanip>
double d = 12.345678;
double e = 2011;
double f = 1e-10;
cout << d
<< e
<< f
<< setprecision(4)
<< d
<< e
<< f
<< fixed
<< d
<< e
<< f
<< scientific
<< d
<< e
<< f
<< true <<' '<< false
<< boolalpha
<< true <<' '<< false;
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