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

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

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

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

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

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...