Question

I have a problem when trying to write a matrix into a file. I manage to open a text file however instead of a 3x3 matrix being displayed there's a long number that is an error.

The code I have is

outf.open("Out2.txt");
            cout<<"Please enter the output file(Out2.txt\n";
            cin>>outfile;
            if (outfile == "Out2.txt"); 
            {                                       
            outf<<"The sum of Matrix X and Matrix Y is:"<<sum[3][3]; 
                }               
            outf.close();

The solutions probably very trivial but I haven't been able to find the solution online!

Was it helpful?

Solution

You need to write out the matrix elements individually

out << sum[0][0] << "," << sum[0][1] << etc.

OTHER TIPS

the line

outf<<"The sum of Matrix X and Matrix Y is:"<<sum[3][3]; 

write to file the content of the cell at 4th line and 4th column.

As said David Sykes, you should iterate to write all cells:

for(int lin=0;line<nb_lines;lin++)
{
    for(int col=0;col<max_col;col++)
    {
         ouf << sum[lin][col] << " " ;
    }
    ouf << std::endl ;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top