【发布时间】:2019-02-01 10:22:41
【问题描述】:
我正在编写一个模拟掷骰子的程序,但我被这段代码卡住了:
short diceNumber(){
unsigned short dice;
do {
printf("\nInput the number of dice to roll: ");
if(!scanf("%hu", &dice)) {
scanf("%*[^\n]");
scanf("%*c");
puts("");
puts("WRONG INPUT!");
}
else if(dice <= 0) puts("YOU MUST USE A DICE AT LEAST!");
}while(!scanf("%hu", &dice)|| dice <= 0);
return dice;
}
问题在于 if 语句中的“scanf”需要两个输入而不是一个,例如:
Input the number of dice to roll: 2
然后它再次想要 2(或其他数字)。不扫描第一个输入。但以前,在另一个函数中,“相同”语句正在工作。代码如下:
void menu () {
unsigned short myAnswer;
puts("Choose the dice type");
puts("");
// A printf statement with all the options
puts("");
do {
// INPUT VALIDATION SECTION
printf("\nYour input: ");
if (!scanf("%hu", &myAnswer)) {
scanf("%*[^\n]");
scanf("%*c");
puts("");
}
// switch statement
} while (myAnswer < 1 || myAnswer > 17);
}
我尝试了不同的解决方案(如 fputs、fflush(stdin)、fflush(stdout)),但没有一个能奏效。你能帮帮我吗?
【问题讨论】:
-
你在用三个
scanf调用做什么,我猜是处理无效输入并跳过该行的其余部分?那么为什么不简单地将整行读取到缓冲区中,然后在该缓冲区上使用sscanf? -
至于您的问题,您打了多少个
scanf("%hu", &dice)电话?非工作循环和工作循环之间存在非常大的差异(提示:仔细查看它们的条件)。 -
旁白:
!scanf("%hu", &dice)应该是scanf("%hu", &dice) != 1否则您将不会接回EOF。还有dice不能是< 0。 -
@Someprogrammerdude 是的,我使用三个 scanf 调用来处理无效输入。我可以试试 sscanf。
-
@WeatherVane 是的,
标签: c