不是首次输入的话,需要两次才能正确响应
get_choice函数要求输入字母A、B、C、D、Q或者a、b、c、d、q,其他均为非法输入,返回字母a、b、c、d、q。
但是,在第二次以及其后输入字母的时候,不管输入其他什么都会提示“Please input A, B, C, D, Q or a, b, c, d, q.”,需要再次输入才能进行判断;
get_first函数是教材上的一个实例,在该示例中是可以略过回车的,在这里就不行了。
int get_choice(void) { int ch; printf("Please the operation of your choice:\n"); printf("A.add \tB.subtract\n"); printf("C.multiply\tD.divide\n"); printf("Q.quit\n"); ch=get_first(); while((ch<'a'||ch>'d')&&(ch<'A'||ch>'D')&&ch!='q'&&ch!='Q'){ printf("Please input A, B, C, D, Q or a, b, c, d, q.\n"); //不是首次输入的话,任何输入都需要输入两次 ch=get_first(); } if((ch>='A'&&ch<='D')||ch=='Q') ch+=32; return ch;}int get_first(void){ int ch; ch=getchar(); while(getchar()!='\n') continue; return ch;}/**++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ *实例8.8,混合输入字符和数值;菜单技术,使用switch分支语句 *++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */#include <stdio.h>char get_choice(void);char get_first(void);char get_first(void);void count(void);int main(void){ int choice; while((choice=get_choice())!='q'){ switch(choice){ case 'a':printf("Buy low, sell high.\n"); break; case 'b':putchar('\a'); break; case 'c':count(); break; default :printf("Program error!\n"); break; } } printf("Bye!\n"); return 0;}char get_choice(void){ int ch; printf("Enter the letter of your choice:\n"); printf("a.advice\tb.bell\n"); printf("c.count \tq.quit\n"); ch=get_first(); while((ch<'a'||ch>'c')&&ch!='q'){ printf("Please input a, b, c or q: \n"); ch=get_first(); } return ch;}char get_first(void){ int ch; ch=getchar(); while(getchar()!='\n') continue; return ch;}char get_int(void){ int input; char ch; while(scanf("%d",&input)!=1){ while((ch=getchar())!='\n') putchar(ch); printf(" is not an integer, please enter agin.\n"); } return input;}void count(void){ int n,i; printf("Count how for? Enter an integer: \n"); n=get_int(); for(i=1;i<=n;i++) printf("%d\n",i); while(getchar()!='\n') continue;}