What's the difference between while(cin) and while(cin >> num)

不问归期 提交于 2019-11-28 20:40:10

Let's look at these independently:

while(cin >> x) {
    // code
}

This loop, intuitively, means "keep reading values from cin into x, and as long as a value can be read, continue looping." As soon as a value is read that isn't an int, or as soon as cin is closed, the loop terminates. This means the loop will only execute while x is valid.

On the other hand, consider this loop:

while(cin){
    cin >> y;
    //code
}

The statement while (cin) means "while all previous operations on cin have succeeded, continue to loop." Once we enter the loop, we'll try to read a value into y. This might succeed, or it might fail. However, regardless of which one is the case, the loop will continue to execute. This means that once invalid data is entered or there's no more data to be read, the loop will execute one more time using the old value of y, so you will have one more iteration of the loop than necessary.

You should definitely prefer the first version of this loop to the second. It never executes an iteration unless there's valid data.

Hope this helps!

The difference is that if cin >> whatever evaluates to false, your second version still runs the rest of the loop.

Let's assume cin >> whatever fails. What will happen?

while(cin >> x){
    // code that DOESN'T RUN
}

while(cin){
    cin >> y;
    //code that DOES RUN, even if the previous read failed
}
while(cin >> x){
    // code
}

This reads integers until it encounters a non-integer, EOF, or other stream error. Whenever you use x inside the loop, you know it has been read successfully.

while(cin){
    cin >> y;
    //code
}

This reads integers until it encounters a non-integer, EOF, or other stream error. However, the stream is only checked before reading the integer. When you use y in the loop, you can't guarantee that it was successfully read.

cin >> x will store the input value into x.

As for while(cin), std::cin will return a boolean on whether an error flag is set. Therefore, you will continue in the while loop so long as std::cin has no error flag set internally. An error flag can be set if it finds an end of file character, or if it failed to read and store into the value.

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