使用缓冲

C Primer Plus 第8章 字符输入/输出和输入确认 8.5 创建更友好的界面

家住魔仙堡 提交于 2019-12-04 23:42:28
8.5.1 使用缓冲输入 问题在于缓冲输入需要您按下回车键来提交您的输入。这一动作还传输一个程序必须处理的换行符。您必须使程序至少能够处理这种情况 。 程序清单8.4 guess.c程序 /*guess.c--一个低效且错误的猜数程序*/ #include <stdio.h> int main (void) { int guess=1; char response; /*添加一个char变量存储响应*/ 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') /*获取用户响应并和y进行比较*/ { if (response=='n') /*if else 来区别字符n和以个的字符*/ printf("Well,then,is it %d\n",++guess); else printf("Sorry,I understand only y or n.\n");