+ 1
How to read a matrix from a text file in c++?
I wanted to compute the sum of rows and columns of a matrix from a single input text file
8 Answers
0
it is in a text file in notepad and it is arranged like this in a line. it has to be a square matrix
6.00 3.00 4.00 5.00
0
Sorry it has to be like a real square matrix not in a line
6.00 3.00
4.00 5.00
0
First, include <fstream>. Then, create a file input object and open your file. Finally, use the file input object the same way as cin. Close the file after using. For example, assuming you have a variable matrix of dimension n x n and a file with the matrix:
std::ifstream in_file;
in_file.open("foo.txt);
for (size_t i = 0; i < n; ++i)
{
for (size_t j = 0; j < n; ++j)
{in_file >> matrix[i][j];}
}
in_file.close();
Later, when you get more experienceâ, you can use exception handling to avoid problems with inexistent files or other errors.
0
thank you, but the text files are test cases meaning they are already established in their matrix sizes. the code should be able to run any square matrix that is stored in as a text file.
0
You mean you need to read N from the text or you input it by yourself?
0
from a text