lesolorzanov
lesolorzanov

Reputation: 3606

load float/double matrix from txt using c++

It seems pretty dumb, but I am having a hard time loading a matrix type double I have on a txt file. inside it has signed doubles things like

11707.2 -919.303 -322.04 2260.71 2443.85 -4629.31 3082.64 -4209.86
-1741.71 298.192 -5658.34 2377.03 -3039 -2049.99 2788 -1915.9 

and so on, and I have it in a txt file.

I have used fscanf, ifstream and all sorts of things I have found and am familiar with, but I have not been able to load it. I found on related question but the procedure didnt help me.

I need to save those values to a float array, but right now I just want to be able to load them correctly, all values look like the ones I wrote.

help please? any one?

Related question: Reading a .txt text file in C containing float, separated by space

Upvotes: 1

Views: 1463

Answers (1)

Kerrek SB
Kerrek SB

Reputation: 477110

Standard idiom:

#include <fstream>   // for std::ifstream
#include <sstream>   // for std::istringstream
#include <string>    // for std::string and std::getline

int main()
{
    std::ifstream infile("thefile.txt");
    std::string line;

    while (std::getline(infile, line))
    {
        // process line, e.g. one matrix per line:

        std::istringstream iss(line);
        std::vector<double> m;
        m.reserve(16);
        double d;

        if (iss >> d) { m.push_back(d); }
        else { /* error processing this line */ }

        if (m.size() != 16) { /* error */ }

        // use m
    }
}

If your matrix data is spread out over multiple lines, modify the code accordingly.

Upvotes: 3

Related Questions