Introduction To C++ IO Streams

别说谁变了你拦得住时间么 提交于 2019-12-01 18:05:27

cin is an instance of istream template class. operator >> acts on this istream instance to load input into data and returns a reference to this istream. Then in while condition it is tested by a call to cin::operator void*() const (explicit operator bool() const in C++11) which invokes fail() function to test if operation succeeded. This is why you can use this operation in while condition

while ( cin >> x)
{
   //...

According to the documentation ( http://www.cplusplus.com/reference/ios/ios/operator_bool/ ), the operator

explicit operator std::ios::bool() const;

"Returns whether an error flag is set (either failbit or badbit)." and "The function returns false if at least one of these error flags is set, and true otherwise."

Thus when the if statement casts the cin stream to bool, this operator returns false if the stream has an error flag set, and true otherwise.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!