Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Looking for help on this C++ program: 1.) Write a program that takes a command l

ID: 3704757 • Letter: L

Question

Looking for help on this C++ program:

1.) Write a program that takes a command line argument for the name of a file. The program then reads two matrices (whose entries are integers) from the file, with both matrices guaranteed to be of the same dimensions. The matrices will be separated from each other in the file by a blank line. The entries in each row of the matrix will be separated by a blank space, with no characters other than spaces and those forming the integers appearing on each separate line. The program then outputs the sum of the two matrices to a file with each row of the matrix on a separate line in the file, and the entries of each row in the matrix separated by a space.

Explanation / Answer

#include <iostream>
#include<fstream>
//no of rows 4 , number of colums 3 , you can change to number of rows and col you want
#define rows 3
#define cols 3
using namespace std;

int main(int argc,char **argv)
{
int matrix1[rows][cols],matrix2[rows][cols];
//input file to read
ifstream in;
//output stream to output matrix
ofstream out;
//check if there are two command line args one for program name and other for name for input file
if(argc < 2)
{
cout<<"Usage: <./program_name(a.out) inputfilename>"<<endl;
return -1;
}
  
//open input file
in.open(argv[1]);
if(!in)
{
cout<<"Not able to open input.txt file"<<endl;
return -1;
}
//read matrix1 , then matrix 2
for(int i = 0; i < rows;i++)
{
for(int j = 0; j < cols;j++)
{
in>>matrix1[i][j];
}
}
for(int i = 0; i < rows;i++)
{
for(int j = 0; j < cols;j++)
{
in>>matrix2[i][j];
}
}
//write sum of matrix to file
out.open("sum_matrix.txt");
if(!out)
{
cout<<"Not able to open file for output"<<endl;
return -1;
}
int sum;
//cout<<"Sum of two matrices is : "<<endl;
out<<"Sum of two matrices is : "<<endl;
for(int i = 0; i < rows;i++)
{
for(int j = 0; j < cols;j++)
{
sum = matrix1[i][j]+ matrix2[i][j];
// check the output file for the sum of matrices

// cout<<sum<<" ";
  
out<<sum<<" ";
}
//cout<<endl;
out<<endl;
}
return 0;
}

---------------------------------------------

//check the output file name for the sum of the two matrices

check the content of the output file sum_matrix.txt for the sum if two matrices

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote