Search code examples
c++arraysvectorfstreamifstream

Reading Text File of Floats into a 2D Vector in C++


I have a data file comprised of thousands of float values and I want to read them into a 2D vector array and pass that vector to another routine once it's stored the floats from the file. When I run this code it prints out;

[0][0] = 0, [0][1] = 0, etc.

The data file contains values like;

0.000579, 27.560021, etc.

int rows = 1000;
int cols = 2;
vector<vector<float>> dataVec(rows,vector<float>(cols));
ifstream in;
in.open("Data.txt");

for(int i = 0; i < rows; i++){
    for(int j = 0; j < 2; j++){
        in >> dataVec[i][j];    
        cout << "[ " << i << "][ " << j << "] = " << dataVec[i][j] << endl;
    }
}
in.close();

Solution

  • It looks to me like the file could not be opened. You did not test for success, so it will plough on regardless. All your values were initialized to zero and will stay that way because every read fails. This is conjecture, I admit, but I'd put money on it. =)