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

后端 未结 6 2110
滥情空心
滥情空心 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 06:49

    does std::cin read input into value first then test the validation of std::cin, or test std::cin first then decide whether to read into 'value'

    cin first tries to read an int from the standard input, if cin is in a good state: if it fails to, it will set the stream to a bad state; regardless of the operation done, it will return the stream itself (i.e. the "left operand" -- cin), that will allow you to check for success or failure.

    If you wanted to explicitly test the validity of the stream first and only then try to read the value, you would have:

    while (cin && cin >> value)
    

    but it's pretty redundant, since, as I've told you, cin will not even try to read value if it's already in a bad state.

提交回复
热议问题