JRYS
JRYS

Reputation: 15

Multidimensional vectors and csv file

Please help me with multidimensional vectors. I have a csv file. what I want is that it will:

  1. read the csv file, place it in a vector of 6 rows and 7 columns.
  2. return the vector.
  3. all of these are placed in a function. not the main function.

Even a simple sample code will do.

I ended up with this, but I got stuck.

vector< vector <string> > THIRDSTEP::DispSched(string movies)
{
    ifstream file("sched1.csv");
    vector < vector<string> > data(7, vector<string>(6));
    while (!file.eof())
    {
        for (int r = 0; r < 7; ++r)
        {
            vector<string> row;
            string line;
            getline(file, line);
            if (!file.good())
                break;
            stringstream iss(line);

            for (int c = 0; c < 7; ++c)
            {
                string val;
                getline(iss, val, ',');
                if (!iss.good())
                    break;

                stringstream convert(val);
                data.push_back(convert);
            }
        }

    }

    return data;
}

Upvotes: 1

Views: 3728

Answers (2)

Jeremy Villegas
Jeremy Villegas

Reputation: 193

You're very close. Try these few modifications:

vector< vector <string> > THIRDSTEP::DispSched(string movies)
{
    ifstream file("sched1.csv");    
    vector < vector<string> > data(7, vector<string>(6));
    // Clear the array since the rows will be initialized with empty string vectors
    data.clear();
    while (!file.eof())
    {
        for (int r = 0; r < 7; ++r)
        {
            vector<string> row;
            string line;
            getline(file, line);
            if (!file.good())
                break;
            stringstream iss(line);

            for (int c = 0; c < 7; ++c)
            {
                string val;
                getline(iss, val, ',');
                if (!iss.good())
                    break;
                // Not needed, since you only need the one value
                //stringstream convert(val);
                row.push_back(val);
            }
            // Since you've built the columns, add the row
            data.push_back(row); 
        }

    }

    return data;
}

Upvotes: 0

Abhishek Bansal
Abhishek Bansal

Reputation: 12715

Try changing your while loop to something like the following.:

string line;
int r = 0;

// We can build the vector dynamically. No need to specify the length here.
vector < vector<string> > data;

// while r < 7 and getline gives correct result
while (r < 7 && getline(file, line))
{
        vector<string> row;
        stringstream iss(line);
        int c = 0;
        string val;

        // while c < 7 and getline gives correct result
        while (c < 7 && getline(iss, val, ','))
        {            
            // no need for converting as you are reading string.
            row.push_back(val);
        }
        data.push_back(row);
}

Upvotes: 3

Related Questions