C 菜单浏览

来源:互联网 发布:盛科网络 营收 编辑:程序博客网 时间:2024/06/05 08:11

许多程序都把菜单作为用户界面的一部分,然后程序根据用户所选项完成任务。作为一名程序员,自然希望这一过程能够顺利进行。因此,第一个目标是:当目标遵循指令程序顺利运行;第二个目标是:当用户没有遵循指令时,程序也能顺利运行。显而易见,要实现第二个目标的难度更大,因为很难预料用户在使用程序时的所有错误情况。

下面看一个有着用户友好特性的菜单浏览程序:

#include<stdio.h>
char get_choice();//用来使函数只返回a,b,c,q,4个选项。
char get_first();//用来获取一串字母中的首字母,读取一行中的首字符并丢弃剩下的字符。例如输入act等同与输入a。
int get_int();//用来获取int型的值而不是其他类型的值
void count();//用来获取数字。
int main()
{
int choice;
while ((choice = get_choice()) != 'q')
{

//swich语句控制了固定数量的选项
switch (choice)
{
case 'a':printf("buy low,sell high.\n");
break;
case 'b':putchar('\a');
break;
case 'c':count();
break;
default:printf("program error!\n");
break;
}
}
printf("bye.\n");
return 0;
}
void count()
{
int n, i;
printf("count how far?enter an integer:\n");
n = get_int();
for (i = 1; i <= n; i++)
printf("%d\n", i);
while (getchar() != '\n')
continue;
}
char get_choice()
{
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()
{
int ch;
ch = getchar();
while (getchar() != '\n')
continue;
return ch;
}
int get_int()
{
int input;
char ch;
while (scanf("%d", &input) != 1)
{
while ((ch = getchar()) != '\n')
putchar(ch);
printf("is not an integer.\nplease enter an ");
printf("integer value,such as 25,-178, or 3:");
}
return input;
}

程序运行结果:

enter the letter of your choice:
a.advice                b.bell
c.count                 q.quit
a
buy low,sell high.
enter the letter of your choice:
a.advice                b.bell
c.count                 q.quit
count
count how far?enter an integer:
two
twois not an integer.
please enter an integer value,such as 25,-178, or 3:2
1
2
enter the letter of your choice:
a.advice                b.bell
c.count                 q.quit
b
enter the letter of your choice:
a.advice                b.bell
c.count                 q.quit
q
bye.
请按任意键继续. . .

0 0