繁体   English   中英

我正在尝试验证用户输入。 但是,如果我输入了无效字符,程序将进入无限循环

[英]I am trying to validate the user input. But if i entered an invalid character the program goes to an infinite loop

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

程序无法运行,进入无限循环。

你能给我什么建议吗,我该怎么做? 谢谢。!!

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


实际结果 :
$ ./每年
插入值:X
插入值:无法读取双精度。 插入值:无法读取双精度。 (循环)...

如果输入无效字符,程序将进入无限循环...如果输入无效字符,则程序将进入无限循环

OP的代码只是试图重新尝试以不断地转换相同的失败数据。

scanf(" %lf", &t) == 0 ,非数字输入保留在stdin ,需要删除。 @尤金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");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM