I'm using C++ to read from two .txt files. The first number in the .txt file represents the rows. The second number represents the columns. Then the remaining numbers is for the matrix. I'm getting an error while trying to scan the dimensions. I tried declaring two ints. I also tried using constants and I still get errors.
This is the requirements to help understand what I'm trying to do. [Matrix Addition1
Here is my code.
#include <iostream>
#include <fstream>
#include<iomanip>
#include<string>
using namespace std;
int main() {
/**
* Integer n and m are declared to store the row and column
* respectively
*/
const int n = 8;
const int m = 8;
int arr[n][m];
//int n, m;
/**
* below we create object of file named myFile for file matrix.txt
*/
string filename;
cout << "Enter file name: ";
getline(cin, filename);
ifstream myfile;
myfile.open(filename.c_str());
/**
* scanning dimensions of first matrix
*/
myfile >> n >> m;
/**
* Creating double type 2d array named matrix1
*/
double matrix1[n][m];
/**
* In following nested for loop we scan data into the array matrix1
*/
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
myfile >> matrix1[i][j];
}
}
cout << "MATRIX 1" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << right << setw(5) << matrix1[i][j];
}
cout << endl;
}
cout << endl;
/***
* Data scanning for matrix 2
*/
/**
* Integer p and q are declared to store the row and column
* respectively of matrix2
*/
const int p = 8;
const int q = 8;
int arr2 [p][q];
//int p, q;
/**
* scanning dimensions of first matrix
*/
myfile >> p >> q;
/**
* Creating double type 2d array named matrix2
*/
double matrix2[p][q];
/**
* In following nested for loop we scan data into the array matrix2
*/
for (int i = 0; i < p; i++) {
for (int j = 0; j < q; j++) {
myfile >> matrix2[i][j];
}
}
cout << "MATRIX 2" << endl;
for (int i = 0; i < p; i++) {
for (int j = 0; j < q; j++) {
cout << right << setw(5) << matrix2[i][j];
}
cout << endl;
}
cout << endl;
/**
* Check if matrix1 and matrix2 can be added
*/
if (n == p && m == q) {
double matrix3[n][m];
for (int i = 0; i < p; i++) {
for (int j = 0; j < q; j++) {
matrix3[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
cout << endl;
cout << "ADDITION of MATRIX 1 AND MATRIX 2" << endl;
for (int i = 0; i < p; i++) {
for (int j = 0; j < q; j++) {
cout << right << setw(5) << matrix3[i][j];
}
cout << endl;
}
cout << endl;
}
else {
cout << "Both matrix cannot be added!" << endl;
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire