Search code examples
c++ofstream

ofstream file does not write


I tried to write my own method to save a Eigen::MatrixXd object in a textfile. However, the file is empty after running this method. While debugging, I saw that the file does not open as I want. Can anyone tell me why?

#include<Eigen\Dense>
#include<iostream>
#include<fstream>
#include<string>

using namespace std;

void savematrix(Eigen::MatrixXd matrix, string filename) {
    int m = matrix.rows();
    int n = matrix.cols();
    ofstream file(filename, ofstream::trunc);
    for (int i = 0; i < m, i++;) {
        for (int j = 0; j < n, j++;) {
            file << m << ";" << n << ";" << matrix(i, j) << endl;
        }
    }
    file.close();
}

int main() {
    Eigen::MatrixXd A(2, 2);
    A(0, 0) = 0;
    A(1, 0) = 1;
    A(0, 1) = 1;
    A(1, 1) = 0;
    cout << A << endl;
    savematrix(A, "savematrixtest.txt");
}


Solution

  • I had a typo a for loop should have looked like that

    for( int i = 0; i < m; i++){}
    

    I did not think of it as my compiler did not give me an error.