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

时间:2014-08-28 14:06:48

标签: c++ linux fstream

我正在尝试读取多个.txt文件并将每行中的每一行push_back转换为string类型的向量。  因此:第一个文件有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;
}

谢谢你有时间帮助我。

4 个答案:

答案 0 :(得分:3)

您需要从 文件中检查文件结尾,检测文件结尾的最佳方法是检查{{1 }}。此代码还直接读入getline()的实例变量,而不是使用中间字符缓冲区。

data

答案 1 :(得分:0)

更改

while(!file_one.eof()&&!file_two.eof())

while(!file_one.eof() || !file_two.eof())

在阅读每个文件之前,你需要检查文件结尾,如果没有什么可读的,请确保你的str1和str2是空的

答案 2 :(得分:0)

您需要修复条件,因为您的条件是“AND”,所以当第一个文件结束时,第二个文件的行根本不会被添加。

为什么不使用单个向量来放置您读过的所有行? 通过这种方式,您可以轻松地分割读取阶段。你将有两个while循环,每个文件一个没有任何其他问题。每次你都会在一个向量 my_data 上进行这种操作:

while(!curr_file.fail()) {
    char buf[max_chars_per_line];
    file_one.getline(buf, max_chars_per_line);
    string str(buf);
    my_data.push_back(buf);
}

答案 3 :(得分:0)

您不应该检查eof(),因为在读取发生之后才会设置此标志。另一件事是使用std::getline()更容易,因为它适用于std::string而不是原始的char缓冲区。并且您不需要其中的两件,如果您愿意,可以重复使用std::ifstream

此外,我不确定是否真的需要存储线路?毕竟文件的长度不同。

也许更像这样的事情会有所帮助:

// file names
string file_1="file1.txt";
string file_2="file2.txt";

// vector to store the lines from the files
std::vector<std::string> my_data;

ifstream file;

std::string line; // working variable for input

file.open(file_1.c_str()); // open first file

while(std::getline(file, line)) // while reading one line is successful
       mydata.push_back(line);

file.close();

// now do the same with the second file

file.open(file_2.c_str());

while(std::getline(file, line))
       mydata.push_back(line);

file.close();

这会将第一个文件中的所有行放入向量,然后将第二个文件中的所有行放入向量中。这种安排与你的安排不同,所以如果它不恰当,只要检查我如何阅读这些内容并将这些信息用于你的目的。

相关问题