C语言问题,各位牛人帮帮我吧

来源:百度知道 编辑:UC知道 时间:2024/06/23 19:17:50
这是我的main()中的一部分
while (1)
{
printf("\nPlease choose from the following:");
printf("\n(1)Start a test\n(2)Check scores\n(3)Exit\n");
scanf("%d",&choice);

switch(choice)
{
case 1: test();break;

case 2: check();break;

case 3: return 0;

default: printf("Wrong,Please try again");
}
因为我要加一个验证函数确定choice必为1,2,3中的一个,而把choice换成字符型的结果每次运行时不管干什么都会先打印
Please choose from the following:
(1)Start a test(2)Check scores(3)Exit
Wrong,Please try again
我都快疯了,怎么也解决不了。。。跪求帮助
我改成字符型时switch里面也改成case '1':case '2':case '3':了

你可以这样:
#include <stdio.h>
#include <stdlib.h>
int main()
{int choice;
......
printf("\nPlease choose from the following:");
printf("\n(1)Start a test\n(2)Check scores\n(3)Exit\n");
while(scanf("%d",&choice)!=1||(choice!=1&&choice!=2&&choice!=3))
{fflush(stdin);
switch(choice)
{
case 1: test();break;
case 2: check();break;
case 3: return 0;
default: printf("Wrong,Please try again");
}
}
......
getch();
return 0;
}
----------------------------------------------------------------------
或者这样:
#include <stdio.h>
#include <stdlib.h>
int main()
{char choice; /* 注意这里 */
......
do{
printf("\nPlease choose from the following:");
printf("\n(1)Start a test\n(2)Check scores\n(3)Exit\n");