Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

What the difference between the following two loops and When each one will stopped ?

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
    int x,y;
    while(cin >> x){
        // code
    }
    while(cin){
        cin >> y;
        //code
    }
    return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
210 views
Welcome To Ask or Share your Answers For Others

1 Answer

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...