首页 > 解决方案 > What does cin >> x evaluate to, on error?

问题描述

Consider this snippet:

int a;
while (cin >> a){/* do something */}

On running this code, suppose I enter a string. The loop is exited. But then, since the expression inside while ends in error, and it doesn't evaluate to a bool type (is this incorrect thinking?), how does the compiler know to exit the loop?

标签: c++c++11

解决方案


cin >> x returns cin to allow chaining.

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.


推荐阅读