Introduction To C++ IO Streams

淺唱寂寞╮ 提交于 2019-12-30 19:16:51

问题


I got a snippet of code from this article and I'm confused as to how it works? The snippet starts by saying:

You can detect that a particular read or write operation failed by testing the result of the read. For example, to check that a valid integer is read from the user, you can do this:

int x;
if ( cin >> x ) 
{
    cout << "Please enter a valid number" << endl;
}

This works because the read operation returns a reference to the stream.

I understand that the cin >> x operation returns a reference to cin but I'm still confused as to how evaluating the reference to the standard input stream object allows you to check that the input is a valid integer.


回答1:


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)
{
   //...



回答2:


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.



来源:https://stackoverflow.com/questions/21713282/introduction-to-c-io-streams

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