将每行中具有不同单词数的文本文件读入C ++中的二维数组

Read text file with different number of words in each line into two dimensional array in C++

因此,我正在尝试将文本文件读入 C++ 中的二维数组。 问题是每行的字数并不总是相同的,一行最多可以包含11个字。

例如,输入文件可能包含:

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

您应该使用 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;
        }
    }

}