不间断的替代 while 循环

Alternative while loop without break

    int number = 0;

   while (scanf("%d",&number)){

       if (sayi == 1 || sayi == 2){
           printf("Login succesful ");
           break;
       }


    }

没有break我怎么写这段代码?

A break 在这里更好。它更密切地暗示了更优化的装配输出。 但是你总是可以使用另一个变量(顺便说一句,你对 scanf 的错误检查是错误的)。

int number = 0;
_Bool not_broken=1;
while (not_broken){
   if (1!=scanf("%d",&number)) {/*handle error*/}

   if (number == 1 || number == 2){
       printf("Login succesful ");
       not_broken = 0;
   }
}

我建议不要尝试将所有内容都塞入 while 条件。它的可读性较差,即使 scanf 失败最终导致跳出循环(例如,如果 /*handle error*/ 部分中有 not_broken=0),您仍然通常想要对错误的响应与对不同输入选择的响应不同。单独的 if 是提供此类单独响应的更简洁的方法。

(我还冒昧地将 sayi 更改为 number,因为使用不相关的变量似乎是编码错误。)

break指令只是一个跳转。您可以改用 goto 语句。但是,使用 goto 不好的做法 。使用 break,您的代码看起来不错。无论如何,这就是你用 goto:

编写它的方式
int number; // removed assignment as it's unnecessary.

while (scanf("%d",&number)) {
    if (number == 1 || number == 2) { // I believe you meant number not sayhi.
        printf("Login succesful ");
        goto break_label;
    }
}

break_label:
// Put other work here, or return 0 if this is the end of the main.

另一种方法是使用@PSkocik 在另一个答案中提到的标志变量。

您可以在 while 条件中使用三元运算符:

while (
       scanf("%d",&number) == 1 && 
       (sayi == 1 || sayi == 2) ? (printf("Login succesful"), 0) : 1
);

您还可以链接 && || 运算符并使用短路:

while (
       scanf("%d",&number) == 1 && 
       !( (sayi == 1 || sayi == 2) && (printf("Login succesful"), 1) )
);

初学者注意while语句中的条件

while (scanf("%d",&number)){
即使 scanf 的调用不成功,

也可以评估为真。所以至少写

是正确的

while (scanf("%d",&number) == 1){

至于循环,那就给你吧。

int number = 0;

while ( number != 1 && number != 2 && scanf("%d",&number) == 1 )
{
    if ( number == 1 || number == 2 ) printf("Login succesful ");
}

注意:sayi 似乎在循环中没有得到改变。所以它的检查最好放在它之外。或者你只是混淆了 number (这更有意义)。请不要 post post 不能反映您问题的代码。


但只是为了转储另一种方法,假设还有什么可以进一步改变循环中的变量 sayi

您还可以使用带有标志变量的 do while 循环:

int i = 1;

do {
       // Anything that changes sayi (related to variable number).

       if ( sayi == 1 || sayi == 2 ) {
           printf("Login successful. ");
           i = 0;
       }

} while ( i || (scanf("%d",&number) == 1 )

旁注:

  • while(scanf("%d",&number)) 是 dangerous/incorrect 好像发生了输入错误,返回值将是 EOF 的负值,这将被评估为 true 和尽管有错误,循环仍在继续。使用 scanf("%d",&number) == 1 作为条件。