首页 > 解决方案 > 将用户输入读取到数组中,直到其最大大小

问题描述

假设max_size数组是 100,我正在尝试将scanf用户输入到数组中,直到输入 EOF。当函数检测到 EOF 时,scanf停止并返回到目前为止输入的元素数。

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;
}

但是,即使我输入了 EOF,它也会i不断增加,直到函数始终返回 100。max_array_size谁能帮我解决这个问题?

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

标签: cscanfstdio

解决方案


首先,让我们明确一点:没有性格这样的东西EOFEOF不作为字符存在,您将无法输入”或“读取”。只是一个任意整数常量,一个库定义的抽象,库函数使用它来表示已到达文件末尾或发生错误。而已。EOFEOFEOF

如果您想确保您所做的事情有意义,请查看scanf手册页

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不会只EOF在到达文件末尾时返回。此外,如果没有发生错误但没有匹配,scanf则可以返回,在这种情况下您也应该停止阅读。0

在这种情况下,您要做的是使用一个简单的for循环,并检查 if scanfreturned 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_twhere needed 而不是int. 在处理大小或索引时,您不希望最终出现由负值引起的错误。


推荐阅读