在函数内部的C程序中,int main()
我有一个while循环,该循环要求用户提供char
输入,并在获取输入后调用方法。获取输入后调用的方法使用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;
}
仅在运行一次该程序之后,贝娄便是一个示例结果:
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
请参阅此处的说明:https : //stackoverflow.com/a/17079227/1755482
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句