c - 整数验证给出无限循环

标签 c validation char scanf

用户需要输入一个整数,然后回车。如果通过验证,则应返回整数,如果未通过验证,则用户应收到错误消息。

当我尝试通过 getInt() 函数验证输入时,我在键入 1 个或多个字符时遇到无限循环。当我键入 abc 时,我得到错误消息的无限循环,而输入 1a 得到正确的验证(1 条错误消息)。我遵循了这个流程图的指示:

getInt() flowchart

代码

  #include <stdio.h>

  void clrKyb(void){
    char input;
    do {
      scanf("%c",&input);
    } while(input !='\n');
  }

  int getInt(void){
    char NL= 'x' ;
    int value ;

    while(NL!='\n'){

      scanf("%d%c",&value,&NL);

      if(NL!='\n') {

       void clrKyb(void);
       printf("Invalid integer, please try again:");

      }

    }   
    return value ;
  }


  int main(void) {
    int iVal;

    printf("Enter an integer: ");
    iVal = getInt();
    printf("You entered: %d\n", iVal);

    return 0;
  }

最佳答案

如评论中所述:

cxw said :

  • getInt 中,void clrKyb(void); 应该只是 clrKyb();,因为你想使用 clrKyb 你已经定义好了。

Jonathan Leffler said :

  • 请注意,在 clrKyB()(和 getInt())中,您需要检查 scanf() 的返回值。如果它返回 EOF,那么再多的重试等也无法阻止无限循环。 (正如 cxw 所指出的,目前在 getInt() 中,您(重新)声明 clrKyB() 并且不调用它 — 这也是一个问题。)

关于c - 整数验证给出无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40289857/

相关文章:

c - C 中的空指针

c - "Dont care"指针?

c - 从 C 中的多个整数创建 String(char*)

javascript - 输入类型 ="number"包含 null 而不是字符

forms - 实现指令以从验证中排除隐藏的输入元素($addControl 问题)

C++ : Turn char array into a string that is printed

c - 使用用户输入在 C 中开发二维数组?

C 参数不起作用?

validation - 在 Magento 中表单验证后更改错误消息

c# - 将字符串拆分为 char 数组的最简单方法