gpt4 book ai didi

c - scanf 来自文件的多个输入

转载 作者:太空宇宙 更新时间:2023-11-04 06:05:35 24 4
gpt4 key购买 nike

我正在尝试从一本未命名的书中学习 C,其中包含以下示例代码:

#include <stdio.h>

int main() {
char word[10];
int i = 0;
while (scanf("%9s", word) == 1) {
i = i+1;
if (i % 2) {
fprintf(stdout, "%s\n", word);
} else {
fprintf(stderr, "%s\n", word);
}
return 0;
}
}

该示例是通过运行

来演示将输出管道化到单独的文件中

./thisprogram < input.txt > output.txt 2> error.txt

并且应该将每隔一个单词输出到相应的文件中。看起来它应该可以工作,但是当我运行它时,只输出第一个单词,而且我不明白为什么 scanf 只取第一个值。我确信我已经正确地复制了代码,但是没有列出这个的勘误表,所以我想知道你们中的任何专家是否可以解释为什么它不起作用以及如何修复它。

最佳答案

return 语句不应该在 while block 中,而是在它之后:

int main() {
char word[10];
int i = 0;
while (scanf("%9s", word) == 1) {
i = i+1;
if (i % 2) {
fprintf(stdout, "%s\n", word);
} else {
fprintf(stderr, "%s\n", word);
}
/* remove this: return 0; */
}
return 0; /* place it here */
}

否则您的程序将在提取第一个单词后退出。

关于c - scanf 来自文件的多个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11059155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com