Ralf Ralf - 1 month ago 10
C++ Question

Adding elements to a 2 dimensional array C++

I’m writing this code where I fill a 2 dimensional array with information from a file. Here’s the file:

5

Franks,Tom 2 3 8 3 6 3 5

Gates,Bill 8 8 3 0 8 2 0

Jordan,Michael 9 10 4 7 0 0 0

Bush,George 5 6 5 6 5 6 5

Heinke,Lonnie 7 3 8 7 2 5 7


Now the numbers are going in the array:
data[50][8]
.

I also total all the numbers in each line which I have done. I want to add this total to the data array so it looks something like
2 3 8 3 6 5 3 30
. How do I do this?
Here’s all my code if you wanted to see it:

int main()
{

ifstream fin;
char ch;
int data[50][8];
string names[50];

fin.open("empdata.txt");

int sum = 0;
int numOfNames;
fin >> numOfNames;

for (int i = 0; i < numOfNames; i++) {

fin >> names[i];

for (int j = 0; j < 7; j++) {
fin >> data[i][j];
}
}

for (int i = 0; i < 5; i++)
{

for (int j = 0; j < 7; j++)
{
sum += data[i][j];

}
cout << sum << endl;
sum = 0;
}
}


Here's the new code that c650 helped me with. It's not outputting anything now:
int main()
{

ifstream fin;
char ch;
int data[50][8];
string names[50];

fin.open("empdata.txt");

int sum = 0;
int numOfNames;
fin >> numOfNames;

for (int i = 0; i < numOfNames; i++) {

fin >> names[i];

data[i][7] = 0;

for (int j = 0; j < 7; j++) {
fin >> data[i][j];
data[i][7] += data[i][j];
}
}

for (int i = 0; i < numOfNames; i++)
{
cout << data[i][7] << endl;

}



system("pause");
return 0;


}

Answer

The following seems like what you are trying to do. I will point the flaws in the code you've presented.

This is not the best way to do it, but according to OP there are some constraints, such as not being able to use the STL.

/*  1 */  #include <fstream>
/*  2 */  #include <iostream>
/*  3 */  #include <string>
/*  4 */  
/*  5 */  using namespace std;
/*  6 */  int main()
/*  7 */  {
/*  8 */  
/*  9 */      ifstream fin;
/* 10 */      int data[50][8];
/* 11 */      string names[50];
/* 12 */  
/* 13 */      fin.open("test.txt");
/* 14 */  
/* 15 */      int numOfNames;
/* 16 */      fin >> numOfNames;
/* 17 */  
/* 18 */      for (int i = 0; i < numOfNames; i++) {
/* 19 */  
/* 20 */          fin >> names[i];
/* 21 */  
/* 22 */          data[i][7] = 0; /* use last spot in array for sum, set to 0. */
/* 23 */          for (int j = 0; j < 7; j++) {
/* 24 */              fin >> data[i][j];
/* 25 */              data[i][7] += data[i][j];
/* 26 */          }
/* 27 */      }
/* 28 */  
/* 29 */      for (int i = 0; i < numOfNames; i++)
/* 30 */      {
/* 31 */          cout << data[i][7] << endl; /* add each element to the sum here*/
/* 32 */      }
/* 33 */      return 0;
/* 34 */  }

OP was having a problem where no output was generated. OP, you must make sure that the your input file has the correct name...