创建一个更友好的用户界面

第一次写博客

getchar函数具有缓冲功能,这在使用中可能会导致一些很傻的现象。

代码如下

//guess.c -- 一个低效且错误的猜数程序 
#include <stdio.h>
int main(void)
{
	int guess = 1;
	printf("Pick an integer from 1 to 100. I will try to ");
	printf("guess it .\nRespond with a y if my guess is ");
	printf("right and with\nan n if it is wrong.\n");
	printf("Uh...is your number %d?\n", guess);
	while (getchar() != 'y')
		printf("well,then,is it %d?\n", ++guess);
	printf("I knew I could do it!\n");
	return 0;
}

运行结果如下

Pick an integer from 1 to 100. I will try to guess it .
Respond with a y if my guess is right and with
an n if it is wrong.
Uh...is your number 1?
n
well,then,is it 2?
well,then,is it 3?
n
well,then,is it 4?
well,then,is it 5?
y

运行结果显示,每次输入n都进行两次猜测。

如果在输入n后加一个[Tab],并按[Enter]

Pick an integer from 1 to 100. I will try to guess it .
Respond with a y if my guess is right and with
an n if it is wrong.
Uh...is your number 1?
n	
well,then,is it 2?
well,then,is it 3?
well,then,is it 4?

运行结果显示,每次输入n时都进行三次猜测。
果然,getchar会把[Tab]、[Enter]之类的输入抓进缓冲里。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值