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;
}
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.
来源:https://stackoverflow.com/questions/19483126/whats-the-difference-between-whilecin-and-whilecin-num