Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the second condition in (cin >> buf && !buf.empty()) redundant? [duplicate]

Tags:

c++

cin

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?

like image 223
Jose_mr Avatar asked Jul 28 '15 17:07

Jose_mr


1 Answers

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 . . .
}
like image 132
Gerry Candy Avatar answered Oct 05 '22 12:10

Gerry Candy