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; }
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..
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 .
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.
On Unix systems, it's ctrl-D .
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With