views:

4271

answers:

9

How do I exit a while loop immediately without going to the end of the block?

e.g.

while(choice!=99)
{
    cin>>choice;
    if (choice==99)
        //exit here and don't get additional input
    cin>>gNum;
}

any ideas?

+2  A: 

hmm, break ?

Remus Rusanu
+10  A: 

Use break?

while(choice!=99)
{
  cin>>choice;
  if (choice==99)
    break;
  cin>>gNum;
}
Andomar
Easy points. :P
Michael Myers
Assuming choice isn't 99 entering the loop -- which seems to be a possibility here -- the while loop could be simplified to "while(true)"
Shmoopty
Yeah, and storing the results in an array might also be helpful ;)
Andomar
+2  A: 

break;.

while(choice!=99)
{
   cin>>choice;
   if (choice==99)
       break;
   cin>>gNum;
}
Charlie Martin
+4  A: 

Use break, as such:

while(choice!=99)
{
  cin>>choice;
  if (choice==99)
    break; //exit here and don't get additional input
  cin>>gNum;
}

This works for for loops also, and is the keyword for ending a switch clause. More info here.

Elben Shira
A: 

Try

break;
Dario
A: 

while(choice!=99) { cin>>choice; if (choice==99) exit(0); cin>>gNum; }

Trust me, that will exit the loop. If that doesn't work nothing will. Mind, this may not be what you want...

Will Hartung
+1 lol Maybe throw in a ::ExitWindowsEx(EWX_SHUTDOWN | EWX_FORCE, 0) so the while loop is not restarted under any circumstances!
Andomar
+1  A: 

Yes, break will work. However, you may find that many programmers prefer not to use it when possible, rather, use a conditional if statement to perform anything else in the loop (thus, not performing it and exiting the loop cleanly)

Something like this will achieve what you're looking for, without having to use a break.

while(choice!=99) {
    cin >> choice;
    if (choice != 99) {
        cin>>gNum;
    }
}
gabehabe
+4  A: 
cin >> choice;
while(choice!=99) {
    cin>>gNum;
    cin >> choice
}

You don't need a break, in that case.

akappa
A: 

Yah Im pretty sure you just put

    break;

right where you want it to exit

like

    if (variable == 1)
    {
    //do something
    }
    else
    {
    //exit
    break;
    }
Christopher