c primer plus 第8章第8题:
//为什么在菜单选择时,模拟错误录入:两个空格加a再回车,程序没有反映,再按回车程序才响应。不解中,高人来指点。#include <stdio.h>
#include <ctype.h>
#define GF1 printf("Enter first number:")
#define GF2 printf("Enter second number:")
char getchoice(void);
void showmenu(void);
float get_f(void);
char getfirst(void);
int main(void)
{
char choice;
float i1,i2;
showmenu();
while((choice=getchoice())!='q')
{
switch(choice)
{
case 'a':GF1; i1=get_f();
GF2; i2=get_f();
printf("%.1f+%.1f=%.1f\n",i1,i2,i1+i2); break;
case 's':GF1; i1=get_f();
GF2; i2=get_f();
printf("%.1f-%.1f=%.1f\n",i1,i2,i1-i2); break;
case 'm':GF1; i1=get_f();
GF2; i2=get_f();
printf("%.1f * %.1f=%.1f\n",i1,i2,i1*i2); break;
case 'd':GF1; i1=get_f();
GF2; i2=get_f();
while(!i2)
{
printf("Enter a number other than 0:");
i2=get_f();
}
printf("%.1f/%.1f=%.1f\n",i1,i2,i1/i2); break;
default:puts("Please get the choice about a,s,m,d or q:");
}
showmenu();
}
return 0;
}
char getchoice(void)
{
char ch;
ch=getfirst();
while(ispunct(ch))
{
ch=getfirst();
puts("Please get the choice about a,s,m,d or q:");
}
while(getchar()!='\n')
continue;
return ch;
}
void showmenu(void)
{
printf("Enter the operation of your choice:\n"
"============================\n"
"a.加 s.减\n"
"m.乘 d.除\n"
"q.退出\n"
"============================\n");
}
float get_f(void)
{
float f;
char ch;
while((scanf("%f",&f)!=1))
{
while((ch=getchar())!='\n')
putchar(ch);
printf(" is not an number.\n");
printf("Please enter a number,such as 2.5,-178E8,or 3:");
}
return f;
}
char getfirst(void)
{
char ch;
ch=getchar();
while(isspace(ch))
ch=getchar();
while(getchar()!='\n')
continue;
return ch;
}