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.
请按任意键继续. . .
- C 菜单浏览
- 《c.primer.plus 5th 》 P208页 菜单浏览
- 【C#】菜单
- Arcengine, C#,属性表浏览
- 【C#】 打开文件浏览窗口
- Internet Explorer 编程简述(八)实现浏览历史菜单
- js菜单伸缩,点击打开弹出浏览窗口
- Internet Explorer 编程简述(八)实现浏览历史菜单
- After Effects动画菜单的浏览预设错误
- C++Primer 读书笔记 第2章 浏览
- C++Primer读书笔记:2 C++浏览
- 一种历史浏览功能的实现(C#)
- Linux下C代码浏览工具--cscope
- C#DataGridView右键菜单
- "效果"(C)菜单
- C++Builder定制系统菜单
- C#,读取Xml生成菜单
- C#,读取Xml生成菜单
- java实现快速排序(利用随机索引)
- NOYJ-拦截导弹
- 你不知道的Java学习笔记20-- 多线程编程
- 1002
- 操作系统
- C 菜单浏览
- Android开发中的Tips
- 杭电 2070 Fibbonacci Number
- 关于数学。
- 关于矩阵表示(matrix-based expression)
- Tcc学习笔记(一) 开篇
- Angular学习心得之directive——require选项的细节
- Linux信号总结
- Apache与Nginx的优缺点比较