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

这是我的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");
choice=getchar();
fflush(stdin);
switch(choice)
{
case '1': test();break;
case '2': check();break;
case '3': return 0;
default: printf("Wrong,Please try again");
}
}while(choice!='1'&&choice!='2'&&choice!='3');
......
getch();
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-01-01
说的明白点
你开关选择的时候 如果是字符 前3个开关都PASS 到 default

因为你原来SCANF输入的时候 CHOOISE就已经是一个int类型的,这个程序可能就是想怎么用开关这个控制语句吧
第2个回答  2009-01-01
如果choice 是字符型

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

case '2': check();break;

case '3': return 0;

default: printf("Wrong,Please try again");
}
第3个回答  2009-01-01
为什么非要用验证函数确定?直接用IF判断一下不就OK了?CHOICE用INT变量不是也可以吗?
第4个回答  2009-01-01
while (1) 一真都是真怎么会变呢?
第5个回答  2009-01-01
请问 '1' = ?
研究一下assci吧 就明白了

数字和字符没有区别

例如 'c' == 'a' + 2;
'a' / 'b' == 0;
相似回答