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

时间:2015-07-28 17:10:43

标签: 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?

1 个答案:

答案 0 :(得分:1)

为了清楚,运算符bool()是badbit || failbit,当“输入操作未能读取预期的charchter或任何其他类型的操作未能产生所需结果时”设置failbit(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 . . .
}