在C++中立即退出'while'循环

Mei*_*eir 13 c++ break while-loop

如何在while不进入块结束的情况下立即退出循环?

例如,

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

有任何想法吗?

And*_*mar 52

用休息?

while(choice!=99)
{
  cin>>choice;
  if (choice==99)
    break;
  cin>>gNum;
}
Run Code Online (Sandbox Code Playgroud)

  • 简单点.:P (17认同)
  • 假设选择不是99进入循环 - 这似乎是一种可能性 - while循环可以简化为"while(true)" (2认同)

aka*_*ppa 8

cin >> choice;
while(choice!=99) {
    cin>>gNum;
    cin >> choice
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,你不需要休息.

  • 所以?"不重复代码"不是你应该以宗教方式遵循的教条.在这种情况下,我发现这种解决方案更自然. (2认同)
  • 复制'cin'没有错.它实际上比这个帖子中的所有其他答案更有效.在while循环中放入if语句会使循环执行两次检查. (2认同)

Elb*_*ira 6

使用break,因此:

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

这也适用于for循环,并且是结束switch子句的关键字.更多信息在这里.