+ 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

6th Sep 2017, 5:48 PM
Sharar Wassey
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
6th Sep 2017, 6:08 PM
Sharar Wassey
0
Sorry it has to be like a real square matrix not in a line 6.00 3.00 4.00 5.00
6th Sep 2017, 6:11 PM
Sharar Wassey
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.
6th Sep 2017, 7:58 PM
Denis Felipe
Denis Felipe - avatar
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.
6th Sep 2017, 8:16 PM
Sharar Wassey
0
You mean you need to read N from the text or you input it by yourself?
6th Sep 2017, 8:27 PM
Denis Felipe
Denis Felipe - avatar
0
from a text
6th Sep 2017, 8:28 PM
Sharar Wassey