10-使用缓冲输入
8.5.1 使用缓冲输入
缓冲输入用起来比较方便,因为在把输入发送给程序之前,用户可以编辑输入。但是,在使用输入的字符时,它也会给程序员带来麻烦。前面示例中看到的问题是,缓冲输入要求用户按下Enter键发送输入。这一动作也传送了换行符,程序必须妥善处理这个麻烦的换行符。我们以一个猜谜程序为例。用户选择一个数字,程序猜用户选中的数字是多少。该程序使用的方法单调乏味,先不要在意算法,我们关注的重点在输入和输出。查看程序清单8.4,这是猜谜程序的最初版本,后面我们会改进。
程序清单8.4 guess.c 程序
/* guess.c -- 一个拖沓且错误的猜数字程序 */
#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') /* 获取响应,与 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
I knew I could do it!
撇开这个程序糟糕的算法不谈,我们先选择一个数字。注意,每次输入 n 时,程序打印了两条消息。这是由于程序读取 n 作为用户否定了数字 1 ,然后还读取了一个换行符作为用户否定了数字 2 。
一种解决方案是,使用 while 循环丢弃输入行最后剩余的内容,包括换行符。这种方法的优点是,能把 no 和 no way 这样的响应视为简单的 n 。程序清单8.4的版本会把 no 当作两个响应。下面用循环修正这个问题:
while (getchar() != 'y') /* 获取响应,与 y 做对比*/
{
printf("Well, then, is it %d?\n", ++guess);
while (getchar() != '\n')
continue; /* 跳过剩余的输入行 */
}
使用以上循环后,该程序的输出示例如下:
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?
no
Well, then, is it 3?
no sir
Well, then, is it 4?
forget it
Well, then, is it 5?
y
I knew I could do it!
这的确是解决了换行符的问题。但是,该程序还是会把 f 视为 n 。我们用 if 语句筛选其他响应。首先,添加一个 char 类型的变量存储响应:
char response;
修改后的循环如下:
while ((response = getchar()) != 'y') /* 获取响应 */
{
if (response == 'n')
printf("Well, then, is it %d?\n", ++guess);
else
printf("Sorry, I understand only y or n.\n");
while (getchar() != '\n')
continue; /* 跳过剩余的输入行 */
}
现在,程序的运行示例如下:
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?
no
Well, then, is it 3?
no sir
Well, then, is it 4?
forget it
Sorry, I understand only y or n.
n
Well, then, is it 5?
y
I knew I could do it!
在编写交互式程序时,应该事先预料到用户可能会输入错误,然后设计程序处理用户的错误输入。在用户出错时通知用户再次输入。
当然,无论你的提示写得多么清楚,总会有人误解,然后抱怨这个程序设计得多么糟糕。