What is the difference between while (cin) and while (cin >> num)

What is the difference between the next two cycles and When will everyone stop?

#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; } 
+8
c ++ iostream
source share
4 answers

Look at them yourself:

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

This loop, intuitively, means "keep reading values ​​from cin to x , and as long as the value can be read, continue the loop." As soon as a value is read that is not int , or as soon as cin closed, the loop ends. This means that the loop will only be executed if x valid.

On the other hand, consider this loop:

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

The while (cin) statement means "while all previous cin operations have succeeded, continue the loop." Once we enter the loop, we will try to read the value in y . It may succeed, or it may fail. However, no matter in which case, the loop will continue to run. This means that after entering incorrect data or not reading data, the loop will run one more time using the old y value, so you will have another loop iteration than necessary.

You should definitely prefer the first version of this cycle to the second. It never iterates if there is no reliable data.

Hope this helps!

+12
source share

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

Suppose 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 } 
+3
source share
 while(cin >> x){ // code } 

It reads integers until it encounters an integer, EOF, or other stream error. Whenever you use x inside a loop, you know that it has been read successfully.

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

It reads integers until it encounters an integer, EOF, or other stream error. However, the stream is checked only before reading the integer. When you use y in a loop, you cannot guarantee that it was successfully read.

+1
source share

cin >> x save the input value to x.

As for while(cin) , std::cin will return a boolean whether the error flag will be set. Therefore, you continue the while loop until std::cin sets the error flag inside. The error flag can be set if it finds the end of file character, or if it could not read and save to value.

0
source share

All Articles