【问题标题】:I am trying to validate the user input. But if i entered an invalid character the program goes to an infinite loop我正在尝试验证用户输入。但是如果我输入了一个无效字符,程序就会进入一个无限循环
【发布时间】:2019-01-21 18:42:29
【问题描述】:

我正在尝试验证用户输入。 如果输入无效,我会尝试要求用户重新插入正确的数字(双精度)值。

程序不工作,进入无限循环。

您能给我一些建议吗?我该怎么做? 谢谢。!!



int main() {

double t; /* Input from user */

int  check;
check = 0;

/* This loop is use to validate the user input.                 *
 * For example: If the user insert a character value "x".       *
 * i am trying to ask the user to insert a valid numeric value. */

while (check == 0)
{
    printf("Insert the value: ");
    if (scanf(" %lf", &t) == 1) {
        check = 1;          /* Everythink okay. No loop needed */
    }
    else
    {
        printf("Failed to read double. ");
        check = 0;          /* loop aganin to read the value */
        fflush( stdout );
    }
}

return 0;

}

预期结果: $ ./a.out
插入值:X
双读失败。
插入值:5


实际结果:
$ ./a.out
插入值:X
插入值:读取双倍失败。插入值:读取双倍失败。 (循环)...

【问题讨论】:

  • 这个X 留在输入流中。您需要将其删除。考虑使用fgets 并对其进行解析(例如使用sscanf)。

标签: c validation input scanf infinite-loop


【解决方案1】:

如果我输入了一个无效字符,程序会进入一个无限循环...如果我输入一个无效字符,程序会进入一个无限循环

OP 的代码只是简单地重新尝试无休止地转换相同的失败数据。

scanf(" %lf", &t) == 0 时,非数字输入仍保留在 stdin 中,需要删除。 @Eugene Sh..

int conversion_count = 0;
while (conversion_count == 0) {
  printf("Insert the value: ");
  // Note: lead space not needed. "%lf" itself consumes leading space.
  // if (scanf(" %lf", &t) == 1) {  
  conversion_count = scanf("%lf", &t); 

  // conversion_count is 1, 0 or EOF
  if (conversion_count == 0) {
    printf("Failed to read double.\n");
    fflush(stdout);

    int ch;
    // consume and discard characters until the end of the line.
    while ( ((ch = getchar()) != '\n') && (ch != EOF)) {
      ; 
    }
    if (ch == EOF) {
      break;
    }
  }
}

if (conversion_count == 1) {
  printf("Read %g\n", t);
}  else {
  printf("End-of-file or input error\n");
}

【讨论】:

  • @Protick 通常最好删除整个非数字行而不是仅删除 1 个字符。 OTOH,您也可以在此处发布您的解决方案作为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-23
  • 1970-01-01
相关资源
最近更新 更多