给定下面的输出:
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(quit)。
c.使用本题a和b部分的函数编写一个最小型程序。最小型的意思是,该程序不需要实现菜单中各选项的功能,只需显示这些选项并获取有效的响应即可。
Code:
#include<stdio.h>
void showmenu(void);//a函数
int getchoice(int,int);//b函数
int main()
{
int res;
showmenu();
while((res = getchoice(1,4)) != 4) //选择按钮,直到选择4按钮quit为止
{
printf("I like choice %d.\n",res);
showmenu();
}
printf("Bye!\n");
return 0;
}
void showmenu(void)
{
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);//输入和类型定义相同 good=1;反之,good=0;
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;
}
return ans;//返回所选按钮数1-4
}