I am following the C++ primer book, and got curious about the following code example:
string buf;
while (cin >> buf && !buf.empty()) {
if (buf[0] != '_')
continue; // get another input
//the input starts with an underscore; process buf . . .
}
The loop should ignore words that do not start with an underscore and do something with the ones that do start with an underscore.
My question is about the condition
(cin >> buf && !buf.empty())
I would say that the condition (!buf.empty()) is always true when (cin >> buf) is true, so I do not see the point of adding it. Is there any case when the second condition is not redundant?
There is a previous question on stack overflow about a similar construction (Is it possible to read an empty string from cin and still get true from cin.good()?) whose answer is simply no (the second condition is redundant).
If this is correct, why is it on the book? It is simply an error? Or there is some special situation were the double condition makes sense?
just to be clear, operator bool() is badbit || failbit, and the failbit is set when "an input operation failed to read the expected charchter or any other kind of operation failed to produce the desired result" (Langer, Kreft 1999)
string buf;
while ((cin >> buf,cin.operator bool()) && !buf.empty()) {
if (buf[0] != '_')
continue; // get another input
//the input starts with an underscore; process buf . . .
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With