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