我编写了以下代码,要求用户从菜单中进行选择。
#include <stdio.h>
char start(void);
char first(void);
float firstn(void);
int main(void)
{
int choice;
while((choice=start())!='q')
{
switch(choice)
{
case'a':
firstn();
printf("yeah\n");
break;
case's':
firstn();
printf("yeah\n");
break;
case'm':
firstn();
printf("yeah\n");
break;
case'd':
firstn();
printf("yeah\n");
break;
}
}
printf("Bye.");
return 0;
}
char start(void)
{
int ch;
printf("Enter the operation of your choice:\n");
printf("a. add s. subtract\n");
printf("m. multiply d. divide\n");
printf("q. quit\n");
ch=first();
while(ch!='a' and ch!='s' and ch!='m' and ch!='d' and ch!='q' and ch!='\n')
{
printf("Please respond with a, s, m, d or q.\n");
ch=first();
}
return ch;
}
char first(void)
{
int c;
c=getchar();
while (getchar()!='\n')
continue;
return c;
}
float firstn(void)
{
float first;
char ch;
printf("Enter first number:");
while(scanf("%f",&first)!=1)
{
while((ch=getchar())!='\n')putchar(ch);
printf(" is not an number.");
printf("Please enter a number, such as 2.5, -1.78E8, or 3:");
}
return first;
}
但是程序运行时,菜单会显示两次,如下所示:
Enter the operation of your choice:
a. add s. subtract
m. multiply d. divide
q. quit
a
Enter first number:3
yeah
Enter the operation of your choice:
a. add s. subtract
m. multiply d. divide
q. quit
a
Enter the operation of your choice:
a. add s. subtract
m. multiply d. divide
q. quit
a
Enter first number:3
yeah
Enter the operation of your choice:
a. add s. subtract
m. multiply d. divide
q. quit
如上所示,程序在第一个循环中运行正常。它从用户那里接收字符,然后询问一个数字。然而,在第二次循环中,程序就出错了。菜单出现过,但无论用户输入什么,菜单都收不到字符,菜单又出现了。只有在菜单出现两次后,菜单才会收到字符。我该如何解决这个问题?
最佳答案
您的 firstn() 函数使用数字,但不使用末尾的换行符。这意味着“3”末尾的换行符将在下一次调用 first() 时使用。它不认为这是选项之一,所以它会再次问你这个问题。
尝试添加:
while (getchar() != '\n');
到您的 firstn() 函数的结尾,就在 return 语句之前。
关于c - 一个程序的菜单出现了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44164021/