Search code examples
c++fileofstream

Reading file, storing in array, error: no match for 'operator>>'


I have a file weights01.txt which is filled with floats in a 4x3 matrix as below

1.1 2.123 3.4
4.5 5 6.5
7 8.1 9
1 2 3.1

I am trying to read this file and transfer the data to an array called newarray. This is the code I am using:

int main()
{
  ofstream myfile;
  float newarray[4][3];
  myfile.open ("weights01.txt");
    for(int i = 0 ; i < 4; i++)   // row loop
    {
        for(int j = 0 ; j < 3; j++)  // column loop
        {
            myfile >> newarray[i][j]; // store data in matrix
        }
    }
  myfile.close();
  return 0;
}

I get an error with the line

myfile >> newarray[i][j];

error: no match for 'operator>>' in 'myfile >> newarray[i][j]'

I do not understand why this error is occuring

I searched for previous questions about this "no match for 'operator>>' error including this and this. I also read this long discussion on overloading operators but I did not find an explanation (possibly because I have not used files much before and don't really follow what is happening.


Solution

  • You cannot read from an std::ofstream (short for out file stream), it is for output only. Use an std::ifstream (that is in file stream) instead.

    If you should ever have questions about which standard library facility does what, check out your favorite reference, for example cppr.


    OT remark: You can directly construct the stream from the filename:

    std::ifstream myfile ("weights01.txt");
    

    and you need not close() the file when you are done, the stream's destructor will handle that for you.