2014-08-28 165 views
1

正在嘗試讀取多個.txt文件並將每行文本中的每行都push_back爲一個字符串類型的向量。因此: :第一個文件有200行。 第二個文件有800行。讀取多個.txt文件C++ linux

但是,我有一個問題,直到它結束讀取第二個文件。

#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; 
} 

感謝您抽出時間來幫我。

回答

0

變化

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

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

你會需要讀取每個文件之前檢查文件結束-,並確保您的str1和str2的是空的,如果有沒什麼可讀的

+1

但是,在檢測到文件結束後,不會'eof()'返回'true',所以在最後一行有可能出現讀取錯誤? – trojanfoe 2014-08-28 14:20:27

+1

這不會工作,因爲條件是錯誤的。 – quantdev 2014-08-28 14:20:40

+0

檢查'eof()'不會像別人指出的那樣做你所期望的。 – Galik 2014-08-28 14:22:39

3

您需要檢查文件結尾要麼文件檢測文件結束的最好方法是檢查getline()的結果。該代碼還直接讀入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); 
} 
0

你需要修復你的條件,因爲你的條件是「與」因此,當第一個文件結束時,第二個文件的行不會在所有加入。

爲什麼你不使用一個單一的載體,你把你讀過的所有線? 通過這種方式,您可以輕鬆拆分閱讀階段。你將有兩個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); 
} 
0

你不應該檢查eof(),因爲這標誌未設置直到讀發生之後。另一件事是它更容易使用std::getline(),因爲它適用於std::string而不是原始字符緩衝區。而且你不需要兩件事,如果你喜歡,你可以重新使用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(); 

這會把所有的行從第一個文件到載體中,然後將所有的線從第二個文件到載體。這種安排與你的不同之處在於,如果它不合適,只要檢查一下我如何閱讀這些信息並將其用於你的目的。