-
Two cins in a loop
Hi say i want a while loop, ok and were adding two numbers useing 'cin' statements. I want to add two numbers by the user in the while loop but they have the option to exit by typing '-1'
my while loop would look like this:
while ( num1 != -1)
Now if i put -1 in the first cin statement to end the loop its still asking me for the second number. Would a 'break' statement be what i need. Or do i need to rearange where i put my cin statements.
Thanks for your help.
-
I assume a break statement would work fine - if you checked the value after the first input. There are probably other ways to do it that aren't necessarily better. If you have trouble with the break statement just show your code.
-
Posting the code concerning the statements in question would be better
-
break;
It sounds like break is exactly what you need! My only other suggestion is: Be consistant. Use the exact same code for both input-variable tests. This means that you will have to change to an infinite loop i.e. while(1).
Although while(1) loops seem a little strange. It is extremely common to use while(1) loops with multiple break statements. (A comment at the start of the loop, telling the "reader" how you get out of the infinite loop is usually helpful.)
[EDIT] -
Sometimes you'll see multiple return statements if you want to exit the loop and the function at the same time.
-
Or an if statement that bypasses the second cin if the first was -1