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!
templatetypedef
source share