我编写了以下代码,要求用户从菜单中进行选择。
#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
如上所示,程序在第一个循环中正常工作。它从用户接收角色,然后询问号码。但是,在第二个循环中,程序出错了。菜单已经出现,但无论用户输入什么,菜单都不会收到该字符,菜单会再次出现。菜单出现两次后,菜单才会收到该字符。我该如何解决这个问题?
答案 0 :(得分:1)
你的firstn()函数会消耗数字,但不会消耗最后的换行符。这意味着下一次调用first()会消耗“3”末尾的换行符。它不承认这是一个选项,所以它再次问你这个问题。
尝试添加:
while (getchar() != '\n');
到return语句之前的firstn()函数的末尾。