2016-05-01 70 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我很高兴这有帮助! –