getchar()每次读取一个字符,scanf()可以输入数字,两者一起使用时,常会出现一些错误。
实例1
猜数字小游戏,如果显示的数字是你所想的,输入’y’;否则,输入’N’。
#include <stdio.h>
int main(){
int guess=1;
char response;
printf("pick a number 1-100:\n");
printf("y is right and n is wrong.\n");
printf("is your number:%d?\n",guess);
while((response=getchar())!='y'){
//if-else循环用来过滤用户非'n'的输入
if (response=='n')
printf("is it %d?\n",++guess);
else
printf("Sorry ,I do not understand.\n")
//while循环用来跳过用户多余的输入及换行符
while(getchar()!='\n')
continue;
}
printf("I could do it.\n");
}
程序输出:
pick a number 1-100:
y is right and n is wrong.
is your number:1?
12
Sorry,I do not understand.
w
Sorry,I do not understand.
qu
Sorry,I do not understand.
no
is it 2?
n
is it 3?
y
I could.
实例2
输入一个数,如果输入不正确,请重新输入。
#include <stdio.h>
int main(){
long input;
char ch;
printf("Please input an integer.\n");
//输入错误处理
while(scanf("%ld",&input)!=1){
while((ch=getchar())!='\n')
putchar(ch);
printf(" is not an integer.\n");
printf("Please input an integer.\n");
}
}
程序输出:
Please input an integer.
d
d is not an integer.
Please input an integer.
s
s is not an integer.
Please input an integer.
12