Jack
Jack

Reputation: 241

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

So, I'm trying to read a text file into a two dimensional array in C++. The problem is that the number of words in each line is not always the same, a line can contain up to 11 words.

For example, the input file could contain:

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

Therefore, array[2][1] should contain "TwoOne", array[1][1] should contain "OneOne", etc.

I don't know how to make my program increase the row number every line. what I have obviously is not working:

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

Upvotes: 0

Views: 420

Answers (1)

Anmol Singh Jaggi
Anmol Singh Jaggi

Reputation: 8576

You should use a vector<vector<string>> to store the data as you don't know in advance how much data will be there to read.

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

}

Upvotes: 1

Related Questions