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

时间:2016-05-01 05:13:28

标签: c++ arrays multidimensional-array readfile

所以,我试图用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];
        }
    }
}

1 个答案:

答案 0 :(得分: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;
        }
    }

}