首页 > 解决方案 > 在 C 中使用 switch 语句调用方法后,循环自动运行

问题描述

在函数内部的C程序中,int main()我有一个 while 循环,它要求用户输入 achar作为输入,并在获得输入后调用一个方法。获取输入后调用的方法使用 aswitch打印或调用其他函数。问题是,在第一次运行 while 循环并从用户那里获得输入之后,匹配的情况完成后,while 循环会自动运行一次,而无需等待用户输入任何内容。作为C的新手,这种行为对我来说很奇怪。因此,我想知道我应该如何处理这种情况以防止自动运行while循环并强制程序等待用户向终端输入任何内容?贝娄是我的代码:

void switchFuncs(struct driver *allDrivers, char operation)
{
    int driverCounter = 0;
    char srchDriver[20];
    int birthYear = 0;
    double kolo = 0.00;
    int pKolo = 0;

    convert_file_data_to_struct(allDrivers, &driverCounter);

    switch (operation)
    {
        case 's':
            printf("Case S is called!!!!\n");
            break;
     
        case 'c':
            printf("Case C is called!!!!\n");
            break;
        case 'n':
            newdriver(allDrivers, driverCounter);
            break;
        case 'x':
            exit(0);
            break;
        default:
            printf("What you typed is not a valid operation!!! \n");
            break;
    }

}

int main()
{
    char operation = 't';
    struct driver *allDrivers;
    int flag = 1;

    while (flag == 1) {
        char operation;
        printf("Select the operation you want to do from the following list: \n\n");
        printf("For Summary Type s \nFor Change Name type c \nFor New Name type n \n");
        printf("To Exist From Program type x \n");
        scanf("%c", &operation);
        if( operation == 'x' || operation == 'X') {
            flag = 0;
        }
        allDrivers = (struct driver*) malloc(1500 * sizeof(struct driver));
        switchFuncs( allDrivers, operation );
        free(allDrivers);
    } 
    return 0;
} 

Bellow 是程序运行一次后的示例结果:

Select the operation you want to do from the following list: 

For Summary Type s 
For Change Name type c 
For New Name type n 
To Exist From Program type x 
s
Case S is called!!!!
Select the operation you want to do from the following list: 

For Summary Type s 
For Change Name type c 
For New Name type n 
To Exist From Program type x 
What you typed is not a valid operation!!! 
Select the operation you want to do from the following list: 

For Summary Type s 
For Change Name type c 
For New Name type n 
To Exist From Program type x 

标签: c

解决方案


在 "%c" 之前放一个空格,如下所示:

scanf(" %c", &operation);
       ^
// Space between " and %c

请参阅此处的说明:https ://stackoverflow.com/a/17079227/1755482


推荐阅读