C语言--scanf
关于C语言的scanf,首先看个例子
int get_int(void){ int input; char ch; while(scanf("%d",&input)!=1){ printf("is not an integer,please enter agin\n"); } printf("%d\n",input); return input; }
这个例子中,如果你输入的不是一个数字的话,程序就会陷入死循环,原因: 如果scanf没有成功读取输入就会将其留在输入队列中,所以下次再从输入队列中读取的时候,还是失败,所以循环了
改正:
int get_int(void){ int input; char ch; while(scanf("%d",&input)!=1){ while(getchar()!='\n'){ continue; } printf("is not an integer,please enter agin\n"); } printf("%d\n",input); return input; }
从输入队列中剔除那些有问题的输入
例子:
/** * menu.c * @desc 菜单技术 */ #include <stdio.h> char get_choice(void); char get_first(void); int get_int(void); void count(void); int main(void){ char choice; choice = get_choice(); if(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"); } /** * 获取一个整数型的输入 */ int get_int(void){ int input; printf("Please input a int:\n"); while(scanf("%d",&input) != 1){ printf("input error,Please input again:\n"); while(getchar() != '\n'){ continue; } } return input; } /** * 获取用户输入字符串的第一个字符 */ char get_first(void){ char ch; ch = getchar(); //清空输入队列中的其他字符 while(getchar() != '\n'){ continue; } return ch; } char get_choice(void){ char ch; printf("Enter the letter if your choice:\n"); printf("a. advice b. bell\n"); printf("c. count q. quit\n"); ch = get_first(); while((ch < 'a' || ch > 'c') && ch != 'q'){ printf("Please choice a b c or q\n"); ch = get_first(); } return ch; } void count(void){ int n,i; printf("Count how far? Enter a integer:\n"); n=get_int(); for(i=1;i<=n;i++){ printf("%d\n",i); } while(getchar() != '\n'){ continue; } }