C 学以致用 输入输出中的坑

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值