2016-05-01 67 views
0

因此,我試圖將文本文件讀入C++中的二維數組中。 問題是,每行中的單詞數量並不總是相同的,一行最多可包含11個單詞。在C++中將每行中不同數量的文本文本文件讀入到二維數組中

例如,輸入文件可包含:

ZeroZero ZeroOne ZeroTwo ZeroThree 
    OneZero  OneOne 
    TwoZero  TwoOne  TwoTwo 
    ThreeZero 
    FourZero FourOne 

因此,陣列[2] [1]應包含 「TwoOne」,陣列[1] [1]應包含 「OneOne」 等。

我不知道如何讓我的程序每行增加行號。我有什麼明顯是不工作:

string myArray[50][11]; //The max, # of lines is 50 
ifstream file(FileName); 
if (file.fail()) 
{ 
    cout << "The file could not be opened\n"; 
    exit(1); 
} 
else if (file.is_open()) 
{ 
    for (int i = 0; i < 50; ++i) 
    { 
     for (int j = 0; j < 11; ++j) 
     { 
      file >> myArray[i][j]; 
     } 
    } 
} 
+0

通過'getline()'讀取線條和分割應該是一種方式。 – MikeCAT

+0

你爲什麼不使用'vector >'? –

+0

@barakmanos我想它應該是'vector > – MikeCAT

回答

1

您應該使用vector<vector<string>>來存儲數據,你事先不知道多少數據將如何在那裏閱讀。

#include <iostream> 
#include <sstream> 
#include <fstream> 
#include <vector> 
using namespace std; 

int main() 
{ 
    const string FileName = "a.txt"; 
    ifstream fin (FileName); 
    if (fin.fail()) 
    { 
     cout << "The file could not be opened\n"; 
     exit (1); 
    } 
    else if (fin.is_open()) 
    { 
     vector<vector<string>> myArray; 
     string line; 
     while (getline (fin, line)) 
     { 
      myArray.push_back (vector<string>()); 
      stringstream ss (line); 
      string word; 
      while (ss >> word) 
      { 
       myArray.back().push_back (word); 
      } 
     } 

     for (size_t i = 0; i < myArray.size(); i++) 
     { 
      for (size_t j = 0; j < myArray[i].size(); j++) 
      { 
       cout << myArray[i][j] << " "; 
      } 
      cout << endl; 
     } 
    } 

} 
+1

謝謝!我不知道向量,這就是我試圖使用數組的原因。我想我必須做一些關於載體的研究。你的回答非常有幫助。再次感謝! – Jack

+0

@Jack我很高興這有幫助! –