Write a program that reads from an external file, conducts necessary evaluations
ID: 3773789 • Letter: W
Question
Write a program that reads from an external file, conducts necessary evaluations and then stores the result in another file. The program should be capable of using the 'command line interface.' Specifically, this assignment involves the following: Show whole program in C++ Make a file called 'input.txt' using a notepad and place it in the same folder you are planning to place your C++ coded program. The file contains the following: The program should be able to do the following: Read the contents of the file 'input.txt, ' Initialize an 'int' type matrix with the contents of the input.txt, Calculate the average of each row and each column, Write a file called 'output.txt' printing the output as shown: The program should work with the command line interface so that one can run the program using a command like:Explanation / Answer
// C++ code
#include <iostream>
#include <fstream>
#include <string>
#include <cassert>
#include <iomanip> // std::setprecision
#include <math.h>
#include <vector>
#include <algorithm>
#include <ctime>
using namespace std;
int main(int argc, char const *argv[])
{
int row = 5;
int column = 5;
int matrix[row][column];
ofstream outputFile (argv[2]);
ifstream inputFile (argv[1]);
if (inputFile.is_open())
{
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < column; ++j)
{
inputFile >> matrix[i][j];
}
}
inputFile.close();
}
else
{
cout << "Unable to open file ";
return 0;
}
double rowAvg[row];
double colAvg[column];
for (int i = 0; i < row; ++i)
{
rowAvg[i] = 0;
for (int j = 0; j < column; ++j)
{
rowAvg[i] = rowAvg[i] + matrix[i][j];
}
rowAvg[i] = rowAvg[i]/row;
}
for (int i = 0; i < column; ++i)
{
colAvg[i] = 0;
for (int j = 0; j < row; ++j)
{
colAvg[i] = colAvg[i] + matrix[j][i];
}
colAvg[i] = colAvg[i]/row;
}
// output to file
outputFile << setw(65) << "Average ";
for (int i = 0; i < row; ++i)
{
for (int j = 0; j < column; ++j)
{
outputFile << setw(10) << matrix[i][j];
}
outputFile << setw(10) << rowAvg[i] << endl;
//outputFile << endl;
}
outputFile << "Avg:";
for (int i = 0; i < column; ++i)
{
outputFile << setw(9) << colAvg[i];
}
outputFile.close();
return 0;
}
/*
output.txt:
Average
7 55 -1 100 56 43.4
5 9 99 1000 56 233.8
59 12 47 8 0 25.2
9 75 10 -7 -9 15.6
-4 3 7 -7 25 4.8
Avg: 15.2 30.8 32.4 218.8 25.6
input.txt
7 55 -1 100 56
5 9 99 1000 56
59 12 47 8 0
9 75 10 -7 -9
-4 3 7 -7 25
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.