How do I use a file called dados.txt as input data for multiplication of two arrays?
That is, I do not want to use cin, but read the data file dados.txt
#include <iostream>
#include <fstream>
#define MAX 100
using namespace std;
int main()
{
int A[MAX][MAX], B[MAX][MAX], C[MAX][MAX];
int m, n, p, i, j, k, aux;
ifstream arquivo;
arquivo.open("dados.txt");
while (arquivo >> aux)
{
//cin >> m >> n >> p;
//read dados.txt
for (i = 0; i < m; i++)
for (j = 0; j < n; j++)
cin >> A[i][j];
for (i = 0; i < n; i++)
for (j = 0; j < p; j++)
cin >> B[i][j];
for (i = 0; i < m; i++)
for (j = 0; j < p; j++)
{
C[i][j] = 0;
for (k = 0; k < n; k++)
C[i][j] += A[i][k] * B[k][j];
}
for (i = 0; i < m; i++)
{
for (j = 0; j < p; j++)
cout << C[i][j] << " ";
cout << endl;
}
}
arquivo.close();
return 0;
}
dados.txt The file contains the following data (example):
3 5 4
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
You’re already reading from the file through the filestream that you declared, arquivo. Instead of doing cin >> A[i][j], you just do arquivo >> A[i][j]. But you also need to take out arquivo >> aux from the while condition. The way you have it setup, it seems you know exactly how long the loop will be. You don’t really even need the while loop. That part of the code can just be: