Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read numbers from a file in C++?

My main question is about how you read data from a file that is not of the char data type. I am writing a file of data from MATLAB as follows:

x=rand(1,60000);
fID=fopen('Data.txt','w');
fwrite(fID,x,'float');
fclose(fID);

Then when I try to read it in C++ using the following code "num" doesn't change.

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    fstream fin("Data.txt",ios::in | ios::binary);
    if (!fin)
    {   
        cout<<"\n Couldn't find file \n";
        return 0;
    }
    float num=123;
    float loopSize=100e3;
    for(int i=0; i<loopSize; i++)
    {
        if(fin.eof())
        break;

        fin >> num;
        cout<< num;
    }
    fin.close();
    return 0;
}

I can read and write file in matlab fine, and I can read and write in c++, but I can't write in matlab and read in c++. The files I write in matlab are in the format I want, but the files in c++ seem to be writing/reading the numbers out at text. How do you read a series of floats in from a file in C++, or what am I doing wrong?

edit: The loop code is messy because I didn't want an infinite loop and the eof flag was never being set.

like image 472
user1860611 Avatar asked Dec 27 '22 13:12

user1860611


1 Answers

Formatted I/O using << and >> does indeed read and write numeric values as text.

Presumably, Matlab is writing the floating-point values in a binary format. If it uses the same format as C++ (most implementations of which use the standard IEEE binary format), then you could read the bytes using unformatted input, and reinterpret them as a floating-point value, along the lines of:

float f;  // Might need to be "double", depending on format
fin.read(reinterpret_cast<char*>(&f), sizeof f);

If Matlab does not use a compatible format, then you'll need to find out what format it does use and write some code to convert it.

like image 189
Mike Seymour Avatar answered Dec 29 '22 10:12

Mike Seymour