当前位置:嗨网首页>书籍在线阅读

17-使执行更顺利

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

8.7.2 使执行更顺利

当你决定实现这个程序时,就要开始考虑如何让程序顺利运行(顺利运行指的是,处理正确输入和错误输入时都能顺利运行)。例如,你能做的是让“获取选项”部分的代码筛选掉不合适的响应,只把正确的响应传入 switch 。这表明需要为输入过程提供一个只返回正确响应的函数。结合 while 循环和 switch 语句,其程序结构如下:

#include <stdio.h>
char get_choice(void);
void count(void);
int main(void)
{
     int choice;
     while ((choice = get_choice()) != 'q')
     {
          switch (choice)
          {
               case 'a': printf("Buy low, sell high.\n");
                         break;
               case 'b': putchar('\a'); /* ANSI */
                         break;
               case 'c': count();
                         break;
               default:  printf("Program error!\n");
                         break;
          }
     }
     return 0;
}

定义 get_choice() 函数只能返回 'a''b''c''q'get_choice() 的用法和 getchar() 相同,两个函数都是获取一个值,并与终止值(该例中是 'q' )作比较。我们尽量简化实际的菜单选项,以便读者把注意力集中在程序结构上。稍后再讨论 count() 函数。 default 语句可以方便调试。如果 get_choice() 函数没能把返回值限制为菜单指定的几个选项值, default 语句有助于发现问题所在。

get_choice() 函数

下面的伪代码是设计这个函数的一种方案:

显示选项

获取用户的响应

当响应不合适时

提示用户再次输入

获取用户的响应

下面是一个简单而笨拙的实现:

char get_choice(void)
{
     int ch;
     printf("Enter the letter of your choice:\n");
     printf("a. advice            b. bell\n");
     printf("c. count             q. quit\n");
     ch = getchar();
     while ((ch < 'a' || ch > 'c') && ch != 'q')
     {
          printf("Please respond with a, b, c, or q.\n");
          ch = getchar();
     }
     return ch;
}

缓冲输入依旧带来些麻烦,程序把用户每次按下Return键产生的换行符视为错误响应。为了让程序的界面更流畅,该函数应该跳过这些换行符。

这类问题有多种解决方案。一种是用名为 get_first() 的新函数替换 getchar() 函数,读取一行的第1个字符并丢弃剩余的字符。这种方法的优点是,把类似 act 这样的输入视为简单的 a ,而不是继续把 act 中的 c 作为选项 c 的一个有效的响应。我们重写输入函数如下:

char get_choice(void)
{
     int ch;
     printf("Enter the letter of your choice:\n");
     printf("a. advice             b. bell\n");
     printf("c. count              q. quit\n");
     ch = get_first();
     while ((ch < 'a' || ch > 'c') && ch != 'q')
     {
          printf("Please respond with a, b, c, or q.\n");
          ch = get_first();
     }
     return ch;
}
char get_first(void)
{
     int ch;
     ch = getchar();    /* 读取下一个字符 */
     while (getchar() != '\n')
          continue;    /* 跳过该行剩下的内容 */
     return ch;
}