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

I follow the C ++ programming tutorial and found out 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 begin with underscores, and do something with those that begin with underscores.

My condition question

 (cin >> buf && !buf.empty()) 

I would say that the condition (! Buf.empty ()) is always true when (cin β†’ buf) is true, so I don’t see the point of adding it. Is there a case where the second condition is not redundant?

There is a previous question about stack overflows around a similar construct ( 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 in the book? Is this just a mistake? Or is there some special situation where a double condition makes sense?

+6
source share
1 answer

to be clear, the bool () operator is badbit || failbit, and failbit is set when "the input operation could not read the expected charchter or some other type of operation, it was not possible to obtain 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 . . . } 
+1
source

All Articles