I have to write a C++ program that inputs a file containing three arrays which need to be added together. The file needs to have its dimensions on the first line and then the three matrices following it. I can't seem to get off the ground with this. I know how to sum matrices and I know how to input files but I don't know how to specify an array size insed a file. An example would be: 2 3 <-this is the dimension of the array (2 x 3)
1 2 3
4 5 6

Any help would be welcomed.

Step 1: read the two numbers on the first line. Name the variables x and y. Then allocate a 2d array of that size

int x,y;
// read x and y from file not shown here
int **matrix = 0; // this is the matrix you need to allocate

// allocate the rows of the matrix
matrix = new int*[y];
// allocate the columns
for(int i = 0; i < y; i++)
  matrix[i] = new int[x];

// now you should be able to read the remainder of the file into that matrix
// and do other calculations

Thank you very much for th quick response. I think I am having a little more trouble than I thought I would. I am trying to add individual elements of three different arrays to form a fourth 2 x 3 array. example: first element [0][0] + second element [0][0] + third element [0][0] etc. here is what I have and its obviously not correct.

#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iomanip>


using namespace std;

int main()
{   
    
    ifstream inFile;
    ofstream outFile;
    string filename1;
    string filename2 = "OUTPUT.txt";
    
     inFile.open(filename1.c_str());
     
     int x,y;
// read x and y from file not shown here

//Matrix A
int **matrixA = 0; 
matrixA = new int*[y];
for(int i = 0; i < y; i++)
  matrixA[i] = new int[x];


//Matrix B
int **matrixB = 0; 
matrixB = new int*[y];
for(int i = 0; i < y; i++)
  matrixB[i] = new int[x];


//Matrix C
int **matrixC = 0;
  matrixC = new int*[y];
for(int i = 0; i < y; i++)
  matrixC[i] = new int[x];
  
//Matrix d

int matrixD [2][3];
matrixD = matrixA[0][0] + matrixB[0][0] + matrixC[0][0] 
          matrixA[0][1] + matrixB[0][1] + matrixC[0][1]
          matrixA[0][2] + matrixB[0][2] + matrixC[0][2]


    
    
    
    system("PAUSE");
    return EXIT_SUCCESS;
}

First you need to add the code that reads the firs line of the time. The code you posted doesn't do that. Put that code on line 18.

Next, starting on line 41 add code to read the data for each of the three matrices.
Here is a thread that might help you with that code.

This article has been dead for over six months. Start a new discussion instead.