reading matrix from text file in c++ and adding them and then storing them in oother c++ file
Reading Matrix from Text File in C++
#include <iostream>
#include <fstream>
#include <vector>
int main() {
std::ifstream file("matrix.txt");
std::vector<std::vector<int>> matrix;
int rows, cols;
file >> rows >> cols;
for (int i = 0; i < rows; ++i) {
std::vector<int> row;
for (int j = 0; j < cols; ++j) {
int num;
file >> num;
row.push_back(num);
}
matrix.push_back(row);
}
file.close();
// Add matrices and store the result in another matrix
std::vector<std::vector<int>> result(rows, std::vector<int>(cols, 0));
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
result[i][j] = matrix[i][j] + matrix[i][j]; // Add the corresponding elements
}
}
// Store the result in another file
std::ofstream resultFile("result_matrix.txt");
resultFile << rows << " " << cols << std::endl;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
resultFile << result[i][j] << " ";
}
resultFile << std::endl;
}
resultFile.close();
return 0;
}
This C++ program reads a matrix from a text file, adds the matrix to itself, and then stores the result in another file. It uses file input/output operations and vectors to manipulate the matrices.