tags:

views:

116

answers:

3

I dont know why the entire matrix gets stored in the first row itself. The loop does actually get called N times if there are N rows.

and this is matrix.dat

5
1 2 3
1 2 0 100
3 4 0
5 6 -1
0 9 10 11

#include <fstream>
#include <iterator>
#include <vector>
#include <iostream>

int main() {

    std::vector<std::vector<int> > matrix;
    std::ifstream infile("matrix.dat");
    int num_rows;
    infile>>num_rows;

    //If there are 5 rows in the matrix, this loops DOES run 5 times.
    for(int i=0;i<num_rows;i++){
            matrix.push_back(std::vector<int>());
            std::copy(
                            std::istream_iterator<int>(infile),
                            std::istream_iterator<int>(),
                            std::back_inserter(matrix[i])
                            );
    }

    // Printing the size of matrix. This correctly prints the value of num_rows
    std::cout<<matrix.size()<<std::endl;

    // Printing just 1st row, but that contains the entire matrix.
    // Seems like copy always happens to matrix[0] only.

    for(int j=0;j<matrix[0].size();j++)
        std::cout<<matrix[0][j]<<" ";

}
+2  A: 

std::istream_iterator<int>() indicates the end of file. So your copy operation copies the entire contents of the file into the matrix[0].

Evän Vrooksövich
what should I write then?
ajay
+2  A: 

You should use getline to split your input file into separate strings for each line. From there, you can construct an istringstream around the line and parse the row with that.

Frank Krueger
+3  A: 
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>

int main()
{

    std::vector< std::vector< int > > matrix;
    std::ifstream infile( "matrix.dat" );

    std::string s;
    while( std::getline( infile, s ) )
    {
     std::string token;
     std::vector< int > tokenisedLine;
     std::istringstream line(s);
     while( std::getline( line, token, ' ' ) )
      tokenisedLine.push_back( atoi( token.c_str() ) );
     matrix.push_back( tokenisedLine );
    }

    return 0;
}

This code should do what you are after, however it is a little slow, with the copying and creation of all the temporary objects. but for small files like your example this will be fine.

It compiled and worked for me using your test data.

as you can see it uses getline twice the first time is splitting lines based on the \n char, then we use it again using the space char. Therefore you need to use spaces to separate elements when using this code.

Then once we have the token as a string we use atoi to convert it to an int.

HTH.

0xC0DEFACE