清除错误的输入

时间:2019-04-06 01:52:32

标签: c

do {
     printf("Enter endpoints of interval to be integrated (low hi): ");
     test = scanf("%lf %lf", &low, &hi);

     if (test != 2) {
        badInput(low);
        badInput(hi);
        printf("Error: Improperly formatted input");
     }

     else if(low > hi)
        printf("Error: low must be < hi\n");

} while ((test != 2 || low > hi));

在这段代码中,我试图消除用户输入错误。目前,我的问题是,如果用户输入字母而不是数字,则提示只是重复而没有让新用户输入。

为了避免这种情况,我需要在函数badInput中添加什么?

1 个答案:

答案 0 :(得分:0)

  
    

当前,我的问题是,如果用户输入字母而不是数字,则提示只是重复而没有让新用户输入。

  

scanf()需要用户两次输入:

test = scanf("%lf %lf", &low, &hi);

当您输入字母而不是数字作为scanf()的输入时,它不会消耗它们,因为它们与给定的格式字符串不匹配,并将它们留在输入缓冲区中。您必须注意,当您使用字母而不是数字时,scanf()必须返回0,因为它不会消耗它们。由于scanf()不会消耗无效输入,因此在循环scanf()的下一次迭代中,在缓冲区中找到未使用的无效输入,然后再次跳过它们。这就是为什么在输入字母作为输入时,程序不会停止输入的原因。要解决此问题,您必须将无效输入从缓冲区中清空。您可以这样做:

do {
    printf("Enter endpoints of interval to be integrated (low hi): ");
    test = scanf("%lf %lf", &low, &hi);

    if (test != 2) {
        badInput(low);
        badInput(hi);
        printf("Error: Improperly formatted input");
        int c;
        while((c = getchar()) != '\n' && c != EOF)  // <=== This loop read the extra input characters and discard them
            /* discard the character */;
    }
    ......
    ......
相关问题