c - 将用户输入读取到数组中,直到其最大大小
问题描述
假设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
谁能帮我解决这个问题?
编辑:显然,我将随机值存储到我的数组中,而不是用户输入的内容。
解决方案
首先,让我们明确一点:没有性格这样的东西EOF
。EOF
不作为字符存在,您将无法“输入”或“读取”。只是一个任意整数常量,一个库定义的抽象,库函数使用它来表示已到达文件末尾或发生错误。而已。EOF
EOF
EOF
如果您想确保您所做的事情有意义,请查看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 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
where needed 而不是int
. 在处理大小或索引时,您不希望最终出现由负值引起的错误。
推荐阅读
- arm - Vulkan/MoltenVK 可以在 armv7s 下运行吗
- javascript - 在 Firebase 云函数中放置初始化代码的位置?
- scala - 使用 scala spark 应用自定义模式以从 rest api 发布响应 JSON
- html - 查看未解释为变量的变量
- android-studio - Android Studio 中的设置
- deployment - 无法将 Windows 内核驱动程序部署到虚拟机
- php - API 未获取信息
- matlab - 在 Matlab 中使用递归逼近 pi
- javascript - Flash 消息未显示在页面重定向上
- powerbi - 按列乘以度量而不聚合后者