我正在尝试读取多个 .txt 文件并将每个文本的每一行 push_back 到字符串类型的 vector 。 因此:第一个文件有 200 行。 第二个文件有 800 行。
但是,我无法读取第二个文件直到它结束。
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <vector>
using namespace std;
struct data
{
string from_file_1;
string from_file_;
};
int main()
{
data my_data;
string file_1="file1.txt";
string file_2="file2.txt";
ifstream file_one(file_1.c_str);
ifstream file_two(file_2.c_str);
Vector<data> mydata;
int max_chars_per_line=100000;
while(!file_one.eof()&&!file_two.eof())
{
char buf[max_chars_per_line];
file_one.getline(buf, max_chars_per_line);
string str(buf);
char buf2[max_chars_per_line];
file_two.getline(buf2, max_chars_per_line);
string str2(buf2);
my_data.from_file_1=str;
my_data.from_file_2=str2;
mydata.push_back(my_data);
}
//when loop exits, the size of the vector ,mydata, should be greater than 200+, but doesn't work .
return 0;
}
感谢您花时间帮助我。
最佳答案
您需要检查任一文件中的文件结尾,检测文件结尾的最佳方法是检查的结果获取行()
。此代码还直接读入 data
的实例变量,而不是使用中间字符缓冲区。
Vector<data> mydata;
data data;
while (getline(file_one, data.from_file_1) &&
getline(file_two, data.from_file_2))
{
mydata.push_back(data);
}
关于c++ - 读取多个 .txt 文件 c++ linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25550861/