What specifically is the bool converting from? |
There's a lot going on:
Think about this statement for a moment:
std::cout << "hello" << ' ' << "world\n";
If you go to your favorite reference page (e.g.
http://en.cppreference.com/w/cpp/language/operator_precedence ) and look up the associativity of the operator<<, you'll find that it is left-associative, and so the statement above is semantically equivalent to
(((std::cout << "hello") << ' ') << "world\n");
In order to get this to print "hello", then a space, then "world", the result of
(std::cout << "hello")
must be
std::cout
itself, or at least look like it. That implies that
((std::cout << "hello") << ' ')
is similarly
std::cout
itself, or close, and the entire full-expression
(((std::cout << "hello") << ' ') << "world\n")
is also
std::cout
.
The same idea is applied to all other streams, too, no matter which way the arrows face, or what the names are. This includes
src
in your code above:
(src >> buf)
results in
src
itself, or something close to it.
This technique is called "method chaining", and the point of this is to show that for any stream -
std::cin, any
std::istream,
std::ifstream,
std::cout,
std::ostream,
std::ofstream, etc.: the expressions
input_stream >> variable
; and
output_stream << variable
result in
input_stream and
output_stream respectively.
Every stream has an error state, and can be converted into a
bool. If the stream is in an error state, then an I/O operation upon the stream does nothing and returns the stream.
If the stream is not in an error state, then an I/O operation upon the stream is attempted. If and only if the I/O operation fails, the stream's error state is set. Then, the stream is returned.
When the stream is converted to
bool, the result is
true if and only if the stream is not in an error state. Otherwise, the result is
false.
In the loop
while (src >> buf)
,
The expression
(src >> buf) is used as a boolean condition. If the stream state is good, the read is attempted and if it is successful,
buf is given the new value, and the loop runs. If the stream state is not good, the read is never attempted and the loop never runs.
Unlike
while (!str.eof()),
the condition above will not result in processing the last element twice, nor will it enter an infinite loop if the read operation fails due to something other than the end-of-file being reached.