io1Code overview
istream& istream::operator>>(int& value)
ios::operator bool() const
!ios::fail()out << setw(n) will invoke out.width(n)I/O Stream Library class hierarchy
std::ios, std::istream, std::cinios_base::iostate flags and ios accessors
ios_base::iostate
fail(): failbit or badbit are setbad(): badbit is seteof(): eofbit is setoperator bool(): equivalent to !fail()Examples runs:
$ echo "10 2 3 4" | ./io1
current sum: 10 fail()==0 bad()==0 eof()==0
current sum: 12 fail()==0 bad()==0 eof()==0
current sum: 15 fail()==0 bad()==0 eof()==0
current sum: 19 fail()==0 bad()==0 eof()==0
final sum: 19 fail()==1 bad()==0 eof()==1
$ echo -n "10 2 3 4" | ./io1
current sum: 10 fail()==0 bad()==0 eof()==0
current sum: 12 fail()==0 bad()==0 eof()==0
current sum: 15 fail()==0 bad()==0 eof()==0
current sum: 19 fail()==0 bad()==0 eof()==1
final sum: 19 fail()==1 bad()==0 eof()==1
$ echo "10 abc 3 4" | ./io1
current sum: 10 fail()==0 bad()==0 eof()==0
final sum: 10 fail()==1 bad()==0 eof()==0
io2sum_ints() rewritten to recover from error
$ echo "10 abc 3 4" | ./io2
current sum: 10 fail()==0 bad()==0 eof()==0
skipped: a
skipped: b
skipped: c
current sum: 13 fail()==0 bad()==0 eof()==0
current sum: 17 fail()==0 bad()==0 eof()==0
final sum: 17 fail()==1 bad()==0 eof()==1
sum_ints() code walk-through
ios::clear(), istream::get()C++ I/O streams vs. C standard I/O
By default, std::cin, std::cout, and std::err are synchronized with stdin, stdout, and stderr. This means that the C++ streams are unbuffered, and each I/O operation on a C++ stream is immediately applied to the corresponding C stream’s buffer. This makes it possible to freely mix C++ and C I/O.
You can turn off this behavior by detaching C++ streams from C streams:
std::ios_base::sync_with_stdio(false);
Possible benefits of detaching C++ streams:
But you lose the following benefits when you detach C++ streams:
'\n' may not flush standard output connected to terminal.Recommendation:
'\n' instead of std::endl for terminal output.io3Code walk-through
f1() version)std::pair class templatef1()operator>>()String stream
Revisit I/O Stream Hierarchy
f2():
getline() reads a line from an istreamistringstream is an istream whose character source is a stringf2() calls f1() not with cin, but with an istringstreamf1()File stream
f3():
ifstream is an istream whose character source is a filef3() calls f2() not with cin, but with an ifstreamf2()ifstream’s RAII paradigm – the constructor opens the file
and the destructor closes it""s denotes an std::string literal