在学完整本书之后,开始重头再复习难题,第一部分,先把课后的复习题中的重难题记录下来,做个笔记,以后每天要坚持写一到两个小时代码。
第八章
C的标准I/O库把不同的文件映射为统一的流来统一处理。
第9章第9题
给定下面的输出:
Please choose one of the following:
1)copy files 2)move files
3)remove files 4)quit
Enter the number of your choice:
a.编写一个函数,显示一份有4个选项的菜单,提示用户进行选择(输出如上所示)。
b.编写一个函数,接受两个Int 类型的参数分别显示上限和下限。该函数从用户的输入中读取整数。如果整数超出规定的上下限,函数再次打印菜单(使用a部分的函数)提示用户输入,然后获取一个新值。如果用户输入的整数在规定范围内,该函数则把该整数返回主调函数,如果用户输入一个非整数字符,该函数应返回4.
c.使用本题a和b部分的函数编写一个最小型的程序。最小型的意思是,该程序不需要实现菜单中各选项的功能,只需显示这些选项并获取有效的响应即可。
答案:
下面是一个最小的程序,showmenu()和getchoice()函数分别是A和B的答案。
#include<stdio.h>
void showmenu();
int getchoice(int,int):
int main()
{
int res;
showmenu();
while((res=getchoice(1,4)!=4)
{
printf("I like choice %d.\n",res);
showmenu();
}
printf("Bye!\n");
return 0;
}
void showmenu()
{
printf("Please choose one of the following:\n");
printf("1)copy files 2)move files\n");
printf("3)remove files 4)quit\n");
printf("Enter the number of your choice:\n);
}
int getchoice(int low,int high)
{
int ans;
int good;
good=scanf("%d",&ans);
while(good==1&&(ans<low||ans>high))
{
printf("%d is not a valid choice;try again\n",ans);
showmenu();
scanf("%d",&ans);
}
if(good!=1)
{
printf("Non-numeric input.");
ans=4;