gpt4 book ai didi

C - scanf() 接受两个输入而不是一个

转载 作者:行者123 更新时间:2023-11-30 16:22:22 26 4
gpt4 key购买 nike

我正在编写一个模拟掷骰子的程序,但我被这段代码困住了:

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)),但没有人工作。你能帮我吗?

最佳答案

The problem is that the "scanf" inside the if statement takes two input instead of one

没有。上面的代码有一组 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;
}

关于C - scanf() 接受两个输入而不是一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54477461/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com