C语言 C 编程 do while 与 switch case 程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26064236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:24:41  来源:igfitidea点击:

C programming do while with switch case program

c

提问by Daler Singh

I have been able to do switch case program but I want program to run again and again until a user selects to quit. I basically wants program to run again and again using do while loop...

我已经能够执行 switch case 程序,但我希望程序一次又一次地运行,直到用户选择退出。我基本上希望程序使用 do while 循环一次又一次地运行......

switch(I)
{
case 1:
    printf("67");
    break;
case 2:
    printf("45");
    break;
default:
    printf("default");
}

回答by Spikatrix

Use a do...whileloop like this:

使用这样的do...while循环:

int I = 1; //Initialize to some non-zero number to prevent UB
printf("Enter 0 to quit \n");
do{
    if (scanf("%d",&I) != 1) //If invalid data such as characters are inputted
    {
        scanf("%*[^\n]");
        scanf("%*c");    //Clear the stdin
    }
} while(I!=0); //Loop until `I` is not 0 

This piece of code will loop until the user enters 0. You can change this code according to your needs. If you want your switchin this, copy your posted code after the scanf.

这段代码会一直循环,直到用户输入0。你可以根据自己的需要更改这段代码。如果你想switch在这个,复制你发布的代码后scanf

回答by user1336087

The loop will run until you enter -1as input.

循环将一直运行,直到您-1作为输入输入。

#include<stdio.h>
int main()
{
    int I;
    do
    {
        puts("Enter -1 to quit");
        printf("Enter your choice: ");
        scanf("%d",&I);
        switch(I)
        {
            case 1:
            printf("67\n");
            break;
            case 2:
            printf("45\n");
            break;
            case -1:
            puts("Bye");
            break;
            default:
            printf("default\n");
        }
    }while(I != -1);
    return 0;
}

回答by Sharad Gaur

Simple Use of Do-While Loop.

Do-While 循环的简单使用。

Choice is the variable in which user's choice will be stored, whether he wants to print the statement again or not.

Choice 是存储用户选择的变量,无论他是否想再次打印语句。

int choice;
do{
   printf("\nHello World!");  //This is the task of the program (Replace it with your task)
   printf("\nDo You Want to Print it again ? 1 Yes/0 No: ");
   scanf("%d",&choice);
}while(choice==1); //Loop will exit when choice gets value other than 1

回答by MD. Khairul Basar

this program runs untill user gives input 0 or a negative number...

该程序运行直到用户输入 0 或负数...

#include<stdio.h>

int main()
{
    int I;
    do
    {
      scanf("%d",&I);
      switch(I)
      {
        case 1:
        printf("67");
        break;
        case 2:
        printf("45");
        break;
        default:
        printf("default");
      }
    }
    while(I>0);
        return 0;
}