c++ - 读取多个 .txt 文件 c++ linux

标签 c++ linux fstream

我正在尝试读取多个 .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/

相关文章:

c++ - C++ 中的短参数类型

linux - 存储在变量或管道到另一个命令时如何保留 grep 颜色?

c++ - 如何使用 linux perf 获取 libc6 符号(例如 _int_malloc)的调用父项?

C++ 在文件中存储对象

c++ - fstream 不会打印到文件

c++ - gluLookAt 不起作用

c++ - 是否可以在 visual studio 2008 64 位版本中使用 boost 库?

c++ - 使用具有传感器融合的 9DOF IMU 在 C++ 中进行双积分加速

mysql - 更新 MySQL root 密码 - Ubuntu

c++ - 如何读取文本文件中的矩阵并将其存储在 C++ 中?