我正在编写一个模拟骰子滚动的程序,而我被这段代码所困扰:
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(或另一个数字)。不扫描第一个输入。但是以前,在另一个函数中,“ same”语句正在运行。这是代码:
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)),但是没有人起作用。你能帮我吗?
答案 0 :(得分:0)
while语句中不应包含scanf。这迫使用户输入一个新号码。
答案 1 :(得分:0)
问题在于if语句中的“ scanf”需要两个输入而不是一个输入
不。高位代码具有一组3 scanf()
和另一个4 scanf()
。导致“采用两个输入而不是一个输入”的是第四种。
3 scanf()
的想法很有价值,即使不寻常,也可以阅读unsigned short
。
要修改代码并仍然采用该主意:
int diceNumber(void) {
unsigned short dice;
for (;;) {
printf("\nInput the number of dice to roll: ");
fflush(stdout); // insure output is seen
int count = scanf("%hu", &dice);
if (count == 1) {
if (dice <= 0) puts("YOU MUST USE A DICE AT LEAST!");
else break;
} else if (count == EOF) { // This case omitted in original code.
return EOF;
}
scanf("%*[^\n]"); // consume almost all of rest of line
scanf("%*c"); // consume rest of line (expected \n)
puts("");
puts("WRONG INPUT!");
// if(dice <= 0) not possible for unsigned short
}
return (int) dice;
}