为什么这个函数会无限循环?

问题描述 投票:0回答:2

当我的用户没有输入正确的输入(在本例中是整数)时,这个函数只是停留在循环中。当用户输入错误的值(如字符串)时,就会发生无限循环。但为什么会出现这种情况呢?以及如何解决这个问题?

int main(void) {
  int colQty;
  int result = 0;
  while (result != 1) {
    printf("Informe a quantidade de colunas: ");
    result = scanf("%d", &colQty);
    if (result != 1) {
      printf("Erro! Verifique se os valores de entrada estão certos.");
    }
  }

  return 0;
}
c gcc scanf infinite-loop
2个回答
3
投票

scanf
在错误输入时停止并且不跳过它。您的代码不断重复扫描相同的输入。通常,最好读取该行和
sscanf
字符串。

char line[100];
printf("\nInforme a quantidade de colunas: ");
if(!fgets(line, sizeof(line), stdin)) {/* handle error */}
result = sscanf(line, "%d", &colQty);

0
投票

正如 @gulpr 所回答的那样,

scanf()
将有问题的输入留在输入流中,因此下一次迭代始终失败而无济于事。同样的问题也会发生在文件末尾,例如,如果输入流从空文件重定向。

建议一次读取一行输入,并使用

sscanf
解析该行中的用户输入。

这是修改后的版本:

#include <stdio.h>

int main(void) {
    int colQty;

    for (;;) {
        char input[100];
        printf("Informe a quantidade de colunas: ");
        if (!fgets(input, sizeof input, stdin)) {
            printf("Error: no input\n");
            return 1;
        }
        if (sscanf(input, "%d", &colQty) == 1) {
            // conversion succeeded, proceed
            break;
        }
        printf("Error: input is not a number: %s", input);
    }
    printf("colQty: %d\n", colQty);
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.