Immediate exit of 'while' loop in C++ [closed]

拟墨画扇 提交于 2019-11-27 23:33:23

问题


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

For example,

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

Any ideas?


回答1:


Use break?

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



回答2:


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

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




回答3:


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.




回答4:


break;.

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



回答5:


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;
    }
}



回答6:


hmm, break ?




回答7:


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...




回答8:


Yah Im pretty sure you just put

    break;

right where you want it to exit

like

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



回答9:


Try

break;



回答10:


You should never use a break statement to exit a loop. Of course you can do it, but that doesn't mean you should. It just isn't good programming practice. The more elegant way to exit is the following:

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

if choice is 99 there is nothing else to do and the loop terminates.



来源:https://stackoverflow.com/questions/872996/immediate-exit-of-while-loop-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!