在switch语句中打破for循环

时间:2016-03-06 03:39:31

标签: c

我有一项功能,系统会提示用户选择三个选项之一。

1.for insert 2.删除 0.for quit

我有一个无限的for循环,它将不断要求用户做某事。但是如果用户选择0,我想要无限循环中断。但是我无法弄清楚如何在switch case中打破for循环。我能设法做到吗?谢谢!

for(;;){
        printf("please enter :\n");
        printf("1 for INSERT\n");
        printf("2 for DELETE\n");
        printf("0 for quit\n");

        printf("what's your value ?\n");
        scanf("%d",&operation);
        switch(operation){
            case 1:
                 printf("you choose to INSERT. Please inter a value to insert\n");
                 scanf("%d",&value);
                 insertAtBeginning(value);
                 break;
            case 2:
                 printf("you choose to DELETE\n");

                 deleteFromBeginning();
                 break;
            case 0:
                  break;
        }
}

4 个答案:

答案 0 :(得分:2)

您可以使用for循环而不是无限while循环,而是检查operation的值,而忽略0个案例:

operation = -1;              // initialize
while (operation != 0) {     // check operation instead
    printf("please enter :\n");
    printf(" 1 for INSERT\n");
    printf("2 for DELETE\n");
    printf("0 for quit\n");

    printf("what's your value ?\n");
    scanf("%d",&operation);
    switch(operation){
        case 1:
             printf("you choose to INSERT. Please inter a value to insert\n");
             scanf("%d",&value);
             insertAtBeginning(value);
             break;
        case 2:
             printf("you choose to DELETE\n");

             deleteFromBeginning();
             break;
    }
}

答案 1 :(得分:1)

也许你可以尝试while(selection!= 0)而不是无限循环

答案 2 :(得分:1)

使用标志来决定何时休息。

bool end = false;

for(;!end;) {
    switch(operation) {
        case 0:
            end = true;
            break;
    }
}

答案 3 :(得分:0)

你可以通过为条件0设置if条件并放置休息来实现它。 if(你的条件== 0) 打破; switch语句中break的含义并不意味着退出for循环,它只是从switch case退出。