将用户输入读取到数组的最大大小

Reading user input into array up to its maximum size

假设数组的 max_size 是 100,我试图 scanf 用户输入数组直到输入 EOF。当函数检测到 EOF 时,scanf 停止并且 returns 到目前为止输入的元素数。

int read_ints_from_stdin(int array[], int max_array_size) { 
    int i = 0, num;
    while ((scanf("%d", &num) != EOF) && i < max_array_size) {
        array[i++] = num;
        printf("value of i is: %d \n", i);
    }
    return i;
}

然而,i 一直在增加,直到 max_array_size 并且函数总是 returns 100,即使我已经进入 EOF。谁能帮我解决这个问题?

编辑:显然,我将随机值存储到我的数组中,而不是用户输入的值。

您需要将 while 循环条件修改为如下内容:

int read_ints_from_stdin(int array[], int max_array_size) { 
    int i = 0, num;
    while ( i < max_array_size) {
        scanf("%d", &num);
        if(num == EOF) break;
        array[i++] = num;
        printf("value of i is: %d \n", i);
    }
    return i;
}

您应该将 number 的值与 EOF 进行比较,而不是 scanf 返回的值。这是因为,scanf returns 分配的成功输入数。在您的代码中,在每次迭代中,scanf 总是重新调整 1(因为该值已分配给 num),稍后将其与 EOF(扩展为 -1)

进行比较

首先,让我们澄清一件事:没有 EOF 字符这样的东西。 EOF作为角色存在,你会 能够“输入EOF”或“读取EOF”。 EOF 只是一个任意整数常量,一个库定义的抽象,库函数使用它来表示已到达文件末尾或发生错误。就是这样。

如果您想确保自己所做的事情有意义,请查看 scanf manual page:

RETURN VALUE
   On success, these functions return the number of input items
   successfully matched and assigned; this can be fewer than provided
   for, or even zero, in the event of an early matching failure.

   The value EOF is returned if the end of input is reached before
   either the first successful conversion or a matching failure occurs.
   EOF is also returned if a read error occurs, in which case the error
   indicator for the stream (see ferror(3)) is set, and errno is set to
   indicate the error.

阅读上面的内容,很明显 scanf 不仅在到达文件末尾时 return EOF。此外,scanf 可以 return 0 如果没有错误但没有匹配,这种情况你也应该停止阅读。

在这种情况下你想要做的是使用一个简单的 for 循环,并检查是否 scanf returned 1,这是唯一的值这对你来说是可以接受的。如果不是,要么到达文件末尾,发生错误,要么输入与格式字符串不匹配:检查错误并采取相应措施。不要压缩 while 条件中的所有错误检查逻辑,这只会令人困惑并且很难正确。

这是一个工作示例,错误检查可能比您实际需要的还要多,但这只是为了让事情更清楚。

size_t read_ints_from_stdin(int array[], size_t max_array_size) { 
    size_t i;

    for (i = 0; i < max_array_size; i++) {
        int res = scanf("%d", &array[i]);
        
        if (res != 1) {
            if (res == EOF) {
                if (feof(stdin)) {
                    // End of file reached, not an error.
                } else {
                    // Real error, print that out to stderr.
                    perror("scanf failed"); 
                }
            } else {
                // Input matching failure.
                fputs("Input does not match requested format.\n", stderr);
            }
            
            break;
        }
    }
    
    return i;
}

另外,请注意在需要的地方使用 size_t 而不是 int。在处理大小或索引时,您不希望因负值而导致错误。