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?
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?
Use break?
while(choice!=99)
{
cin>>choice;
if (choice==99)
break;
cin>>gNum;
}
break;
.
while(choice!=99)
{
cin>>choice;
if (choice==99)
break;
cin>>gNum;
}
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.
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...
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;
}
}
cin >> choice;
while(choice!=99) {
cin>>gNum;
cin >> choice
}
You don't need a break, in that case.
Yah Im pretty sure you just put
break;
right where you want it to exit
like
if (variable == 1)
{
//do something
}
else
{
//exit
break;
}