c - 在 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" 之前放一个空格,如下所示:
scanf(" %c", &operation);
^
// Space between " and %c
推荐阅读
- github - 是否有任何 github 操作可以创建子模块更新的拉取请求?
- html - 为任何类型的 HTML 元素键入自定义 useRef 挂钩
- java - 是否可以有两个 build.gradle 文件?
- powershell - PowerShell 哈希表作为 Azure Devops YAML 管道输出变量
- python - ttk.Checkbutton instate 失败
- python - 如果我同时有一个最大开放,计算哪些票会开放
- sql - SQL查询获取球队的对手数据
- python - 通过 tkinter 绑定函数传递 *args?
- javascript - 用 React.js/JavaScript 中的新元素替换输入或文本区域
- javascript - nanogallery2 如何在单击专辑缩略图后直接打开弹出滑块图像?