cin >> x 在出错时计算什么?

Tra*_*net 2 c++ c++11

考虑这个片段:

int a;
while (cin >> a){/* do something */}
Run Code Online (Sandbox Code Playgroud)

在运行此代码时,假设我输入了一个字符串。退出循环。但是,由于里面的表达式while以错误结束,并且它没有计算为bool类型(这是错误的想法吗?),编译器如何知道退出循环?

Ser*_*sta 7

cin >> x返回cin以允许链接。

And in an boolean context, cin evaluates to true if and only if the last operation was successful.

Long story short, the loop will end on the first end of file or error.