bunduru
bunduru

Reputation: 121

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();

Upvotes: 2

Views: 4276

Answers (3)

Software_Designer
Software_Designer

Reputation: 8587

Try this solution, it works according to your specs:

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

int main(void)
{

    ifstream infile;
    char cNum[10] ;
    int rows = 1;
    int cols = 2;
    vector<vector<float > > dataVec(rows,vector<float>(cols));

    infile.open ("test2.txt", ifstream::in);
    if (infile.is_open())
    {
            while (infile.good())
            {

                for(int i = 0; i < rows; i++)
                {
                    for(int j = 0; j < 2; j++)
                    {

                        infile.getline(cNum, 256, ',');

                        dataVec[i][j]= atof(cNum) ;

                        cout <<dataVec[i][j]<<" , ";

                    }
                }



            }
            infile.close();
    }
    else
    {
            cout << "Error opening file";
    }

    cout<<" \nPress any key to continue\n";
    cin.ignore();
    cin.get();


   return 0;
}

Upvotes: 1

hjbabs
hjbabs

Reputation: 37

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

using namespace std;

void write(int m, int n)
{
    ofstream ofs("data.txt");
    if (!ofs) {
        cerr << "write error" << endl;
        return;
    }

    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            ofs << i+j << " ";
}

void read(int m, int n)
{
    ifstream ifs("data.txt");
    if (!ifs) {
        cerr << "read error" << endl;
        return;
    }

    vector<float> v;
    float a;
    while (ifs >> a) v.push_back(a);

    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            cout << "[" << i << "][" << j << "] = "
                 << v[i*n+j] << ", ";
}

int main()
{
    write(2,2);
    read(2,2);

    return 0;
}

Upvotes: -1

paddy
paddy

Reputation: 63481

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. =)

Upvotes: 6

Related Questions