如何在C中检测用户的无效输入?

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

我需要编写代码,要求您输入介于3-69之间的数字。如果输入不正确,我必须在stderr中打印"wrong input"(如果是字母)或"out of range"(如果它不属于该间隔)。

我可以处理"out of range" stderr,但不能处理另一个。当我输入一个字母时,它会自动转换为一个大数字,这是我认为内存中的某个地址。在这种情况下,stderr变为"out of range",而不是"wrong input"。有没有办法解决?

[将变量引入int也许是错误的?(这些是获取输入的代码行:]

int x, y;
scanf("%i %i",&x,&y);
c input scanf stderr
1个回答
0
投票

当我输入一个字母时,它会自动转换为一个大数字,这是我认为内存中的地址或其他内容。

[xy中都是垃圾。

scanf("%i %i",&x,&y);表示要查找两个整数。如果scanf没有看到两个整数,它将失败并且不会向xy写任何内容。因为您没有检查scanf是否成功,所以当您读取xy时,它们将被初始化。它们将包含当时内存中的所有垃圾。

天真的方法是首先检查scanf是否成功。然后检查数字是否在正确的范围内。为了说明起见,我将问题简化为一个数字。

#include <stdio.h>

int main() {
    int num;
    while(1) {
        if( scanf("%i ",&num) != 1 ) {
            fprintf(stderr, "Please enter a number.\n");
            continue;
        }

        if( num < 3 || 69 < num ) {
            fprintf(stderr, "The number must be between 3 and 69.\n");
            continue;
        }

        break;
    }

    printf("Your number is %i.\n", num);
}

但是当用户输入“ a”时,将进入无限循环。

$ ./test
a
Please enter a number.
Please enter a number.
Please enter a number.

scanf失败时,它将用户输入保留在stdin上。上面的程序将反复读取相同的a。这是scanf的一个普遍问题,它是为结构合理的输入而设计的,而用户输入的结构却不合理。参见the C FAQ for more problems with scanf

相反,请分别阅读和分析。用fgets读整行,用sscanf解析,如果不是您要读的另一行。

#include <stdio.h>

int main() {
    int num;
    char line[1024];
    while(fgets(line, sizeof(line), stdin)) {
        if( sscanf(line, "%i ",&num) != 1 ) {
            fprintf(stderr, "Please enter a number.\n");
            continue;
        }

        if( num < 3 || 69 < num ) {
            fprintf(stderr, "The number must be between 3 and 69.\n");
            continue;
        }

        break;
    }

    printf("Your number is %i.\n", num);
}
© www.soinside.com 2019 - 2024. All rights reserved.