Freopen多文件输入-C++
Freopen Multiple File input - C++
我试过这个
...
for(int i=0;i<totalDoc;i++){
freopen(name[i],"r",stdin);
while(cin>>s!=NULL){doc[i]=doc[i]+s+" ";}
fclose(stdin);
...
}
name
是一个字符"doc1.txt","doc2.txt",…
但是,这个代码只打开"doc1.txt",有人能帮我吗?
您是用C还是用C++编码?你必须选择
您应该阅读freopen(3)的文档并使用其结果。
The freopen() function opens the file whose name is the string pointed to by path and associates the stream pointed to by stream with it. The original stream (if it exists) is closed.
此外,您不应将C++I/O流(例如std::cin
和>>
)与C文件(例如stdin
和fscanf
…)混合使用
我强烈建议你花几个小时阅读更多的文档(在没有阅读文档的情况下,不要使用任何标题、函数或类型)和书籍。你的代码太糟糕了。
因此,您可以在C:中进行编码
for(int i=0;i<totalDoc;i++){
FILE*inf = freopen(name[i],"r",stdin); // wrong
if (!inf) { perror(name[i]); exit(EXIT_FAILURE); }
但这在第二次迭代中不起作用(因为第一次调用freopen
时已经关闭了stdin
),所以您确实希望使用fopen
,而不是freopen
,并从inf
文件中读取。不要忘记在for
循环体的末尾使用fclose
。
顺便说一句,如果你用C++编码(你必须在C和C++之间做出选择,它们是不同的语言),你只需要使用std::ifstream,也许就像一样
for(int i=0;i<totalDoc;i++){
std::ifstream ins(name[i]);
while (ins.good()) {
std::string s;
ins >> s;
doc[i] += s + " ";
};
}
最后,选择您使用的语言和标准(C++11与C99不同),并阅读更多文档。此外,在启用所有警告和调试信息的情况下进行编译(例如,如果使用GCC,则针对C++11代码的g++ -std=c++11 -Wall -g
或针对C99代码的gcc -std=c99 -Wall -g
),并且使用调试器。
正如前面提到的解决方案一样,freopen一次只能用于一个文件。因此,为了绕过C++中的文件IO,我会查看这个源代码并使用fstreams:https://www.bgsu.edu/arts-and-sciences/computer-science/cs-documentation/reading-data-from-files-using-c-plus-plus.html
打开多个文件的一个示例方法是
int a, b;
in.open("file1");
in >> a;
in.close();
in.open("file2");
in >> b;
in.close();
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何只允许用户输入正整数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 输入中的字符串数未知(以字母表示)
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type