Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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; } 
like image 929
Ahmed_Mohsen Avatar asked Oct 20 '13 21:10

Ahmed_Mohsen


People also ask

What is the purpose of the cin >> number statement?

cin >> number tries to read an int from the console and store it in number , then return the stream object ( cin ). If a number could not be read from the stream, the stream will be placed in a fault state and the fail bit is set..

What does while CIN mean in C++?

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 .

Can you put CIN in a while loop?

Well, you use cin inside a while loop when you need the user to enter a value that will be used after that, in the same loop. Everytime the loop runs, the user can chose something else. For example, calculating x*y.

How do you stop a CIN while looping?

On Unix systems, it's ctrl-D .


1 Answers

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!

like image 190
templatetypedef Avatar answered Oct 15 '22 10:10

templatetypedef