在C中退出while循环而不中断

Hai*_*vov 5 c while-loop

我有以下代码:

void takeOrder(void)
{
int stop = 0;
while(stop != 1)
{
    printf("What is your order?\n");
    printf("%c - fruitShake\n%c - milkShake\n", FRUIT_SHAKE_CHOICE, MILK_SHAKE_CHOICE); 
    scanf("%c", &typeChoice); 
    if(typeChoice != FRUIT_SHAKE_CHOICE || typeChoice != MILK_SHAKE_CHOICE)
    {
        printf("***Error! Wrong type***");
        stop = 1;
    }
    //more code below
}
Run Code Online (Sandbox Code Playgroud)

}

我正在尝试使用标志"停止"退出while循环,但它不起作用,它只是继续下面的其余代码.有没有办法退出这个带循环的while循环而不使用break?

das*_*ght 7

你可以用几种方式做到这一点,所有这些都远远不如使用break:

  • 您可以添加else和增加部件的代码嵌套// more code,或
  • 您可以设置变量并使用continue而不是break混淆您的读者,或
  • 您可以添加标签并用于goto激怒您的同事

最好的方法是使用break,并stop完全删除变量,将其替换为"永远"循环:

for (;;) {
    ...
    if (condition) {
        break;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

当三个内置循环都没有给你一个特别好的拟合时,即当在循环的中间做出决定中断或继续时,而不是循环的顶部时,这个结构是惯用的(如在forwhile循环)或循环的底部(如在do/ while循环中).

注意:设置变量时代码不会结束循环的原因是不会连续检查循环条件.而是在每次迭代开始之前检查一次.之后,条件可能在循环体内的任何点变得无效.


Gré*_*EUT 5

唯一的办法我看到的是摆在有条件的more code below部分

 int stop = 0;

 while (stop != 1) {
   if (typeChoice == FRUIT_SHAKE_CHOICE || typeChoice == MILK_SHAKE_CHOICE) {
     stop = 1;
   } else {
     // more code below
   }
 }
Run Code Online (Sandbox Code Playgroud)

使用函数的第二种方法:

while (doStuff() == 0);

int doStuff(void) {
   if (typeChoice == FRUIT_SHAKE_CHOICE || typeChoice == MILK_SHAKE_CHOICE) {
     return 1;
   } 

   // more code below

   return 0;
}
Run Code Online (Sandbox Code Playgroud)

PS:也许我是纳粹分子,但这绝对应该是一个do ... while

 int stop = 0;

 do {
   if (typeChoice == FRUIT_SHAKE_CHOICE || typeChoice == MILK_SHAKE_CHOICE) {
     stop = 1;
   } else {
     // more code below
   }
 } while (stop != 1);
Run Code Online (Sandbox Code Playgroud)