【问题标题】:C - scanf() takes two inputs instead of oneC - scanf() 接受两个输入而不是一个
【发布时间】: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", &amp;dice) 电话?非工作循环和工作循环之间存在非常大的差异(提示:仔细查看它们的条件)。
  • 旁白:!scanf("%hu", &amp;dice) 应该是 scanf("%hu", &amp;dice) != 1 否则您将不会接回 EOF。还有dice 不能是&lt; 0
  • @Someprogrammerdude 是的,我使用三个 scanf 调用来处理无效输入。我可以试试 sscanf。
  • @WeatherVane 是的,

标签: c


【解决方案1】:

问题是 if 语句中的“scanf”需要两个输入而不是一个

没有。上面的代码有一组 3 个scanf() 和另一个第 4 个scanf()。这是导致“需要两个输入而不是一个”的第 4 个。

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;  
}

【讨论】:

  • 我通过从 do...while 循环中删除 scanf 解决了我的代码问题。顺便说一句,我想我会实现这个版本。下次我会尽量记住使用返回值!
【解决方案2】:

您不应该在 while 语句中使用 scanf。这会强制用户输入一个新号码。

【讨论】:

  • 是的,你是对的!两个小时后我就没有在笔记本电脑前了,但我一直在用手机查看代码,感谢@Someprogrammerdude 的建议,我找到了问题所在。顺便谢谢你!
猜你喜欢
  • 2022-01-22
  • 1970-01-01
  • 2021-11-24
  • 2013-12-13
  • 2019-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多