问题描述
- 关于c语言中getchar()的问题
-
#include<stdio.h> int main(void) { int guess = 1; printf("Pick an integer from 1 to 100. I will try to guess"); printf("it. Respond with a y if my guess is right and with"); printf(" an n if it is wrong. "); printf("Uh...is your number %d? ",guess); while (getchar() != 'y') { if (getchar() =='n') printf("Well,then,is it %d? ", ++guess); else printf("Sorry,you say what? "); while (getchar() !=' ') continue; } printf("I knew I could do it! "); 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. Respond with a y if my guess is right and with"); printf(" an n if it is wrong. "); printf("Uh...is your number %d? ",guess); while ((response = getchar()) != 'y') { if (response =='n') printf("Well,then,is it %d? ", ++guess); else printf("Sorry,you say what? "); while (getchar() !=' ') continue; } printf("I knew I could do it! "); return 0; }
为什么这两个程序的运行结果不一样呢??
为什么需要把getchar()的值赋给response?
解决方案
因为每次getchar()都是一个输入数据的动作啊!
把它赋值给response,就能暂存上一个动作的结果了~
第一个程序会造成严重的混乱。
解决方案二:
许多初学者都习惯用?char?型变量接收?getchar、getc,fgetc?等函数的返回值,其实这么做是不对的,并且隐含着足以致命的错误。getchar?等函数的返回值类型都是int?型
下面是getchar()的定义:
[html]?view?plaincopyprint?
?
1?int??
2?getchar?()??
3?{??
4???int?result;??
5?......
答案就在这里:C语言中getchar中的问题
----------------------
时间: 2024-12-10 09:26:57