15

如何while立即退出循环而不走到块的末尾?

例如,

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

有任何想法吗?

4

10 回答 10

56

使用休息?

while(choice!=99)
{
  cin>>choice;
  if (choice==99)
    break;
  cin>>gNum;
}
于 2009-05-16T18:32:09.037 回答
9
cin >> choice;
while(choice!=99) {
    cin>>gNum;
    cin >> choice
}

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

于 2009-05-16T18:44:07.010 回答
6

使用break,例如:

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

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

于 2009-05-16T18:32:25.247 回答
3

break;.

while(choice!=99)
{
   cin>>choice;
   if (choice==99)
       break;
   cin>>gNum;
}
于 2009-05-16T18:32:21.830 回答
3

是的,休息会起作用。但是,您可能会发现许多程序员在可能的情况下不喜欢使用它,而是使用条件 if 语句来执行循环中的其他任何事情(因此,不执行它并干净地退出循环)

这样的事情将实现您正在寻找的东西,而无需使用休息时间。

while(choice!=99) {
    cin >> choice;
    if (choice != 99) {
        cin>>gNum;
    }
}
于 2009-05-16T18:43:21.913 回答
2

嗯,break

于 2009-05-16T18:31:36.433 回答
1
while(choice!=99)
{
  cin>>choice;
  if (choice==99)
    exit(0);
  cin>>gNum;
}

相信我,这将退出循环。如果这不起作用,什么都不会。请注意,这可能不是您想要的...

于 2009-05-16T18:36:12.350 回答
1

是的,我很确定你刚刚放了

    break;

就在你想要它退出的地方

    if (variable == 1)
    {
    //do something
    }
    else
    {
    //exit
    break;
    }
于 2009-05-16T19:13:21.043 回答
0

尝试

break;
于 2009-05-16T18:32:51.190 回答
-2

您永远不应该使用 break 语句来退出循环。你当然可以这样做,但这并不意味着你应该这样做。这只是不好的编程习惯。更优雅的退出方式如下:

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

如果选择是 99,则没有其他事情可做并且循环终止。

于 2011-10-08T15:34:00.917 回答