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

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!

Leave a Comment