#include<stdio.h>
int main(void)
{
int guess = 1;
printf("Pick an integer from 1 to 100. I will try to guess");
printf("it.\nRespond with a y if my guess is right and with");
printf("\nan n if it is wrong.\n");
printf("Uh...is your number %d?\n",guess);
while (getchar() != 'y')
{
if (getchar() =='n')
printf("Well,then,is it %d?\n", ++guess);
else
printf("Sorry,you say what?\n");
while (getchar() !='\n')
continue;
}
printf("I knew I could do it!\n");
return 0;
}
#include<stdio.h>
int main(void)
{
int guess = 1;
char response;
printf("Pick an integer from 1 to 100. I will try to guess");
printf("it.\nRespond with a y if my guess is right and with");
printf("\nan n if it is wrong.\n");
printf("Uh...is your number %d?\n",guess);
while ((response = getchar()) != 'y')
{
if (response =='n')
printf("Well,then,is it %d?\n", ++guess);
else
printf("Sorry,you say what?\n");
while (getchar() !='\n')
continue;
}
printf("I knew I could do it!\n");
return 0;
}
为什么这两个程序的运行结果不一样呢??
为什么需要把getchar()的值赋给response?
许多初学者都习惯用 char 型变量接收 getchar、getc,fgetc 等函数的返回值,其实这么做是不对的,并且隐含着足以致命的错误。getchar 等函数的返回值类型都是int 型
下面是getchar()的定义:
[html] view plaincopyprint?
1 int
2 getchar ()
3 {
4 int result;
5 ......
答案就在这里:C语言中getchar中的问题
----------------------Hi,地球人,我是问答机器人小S,上面的内容就是我狂拽酷炫叼炸天的答案,除了赞同,你还有别的选择吗?
因为每次getchar()都是一个输入数据的动作啊!
把它赋值给response,就能暂存上一个动作的结果了~
第一个程序会造成严重的混乱。