How is “std::cin>>value” evaluated in a while loop?

后端 未结 6 2116
滥情空心
滥情空心 2020-12-11 06:24

Currently I\'m self-learning C++ Primer 5th. Here comes something I\'m not sure. (I couldn\'t find the exact relevant question on F.A.Q).

Consider this while loop:

6条回答
  •  心在旅途
    2020-12-11 07:11

    There are two tests.

    The first test is the condition of the while statement

    while(std::cin>>value){...}
    

    This condition tests the result of calling operator function operator >>

    The second test is a condition within the operator. If the state of the stream std::cin is good then the function tries to read an integer from the string. Otherwise it returns std::cin with the current erroneous state of std::cin.

    In the while condition there is an expression

    std::cin>>value
    

    This expression must be evaluated. So this condition tests the result of the call of operator >> .

    The result of the operator is the stream std::cin But it can be contextually converted to a bool value due to operator

    explicit operator bool() const;
    

    which returns the state of the stream

    !fail().
    

提交回复
热议问题