第一次写博客
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]之类的输入抓进缓冲里。