Hello. After reading other threads that inut from a text file to a basic array I do not understand how to apply it to a 2d array. I dont quite understand what I need to do to make it read in the data properly. This is what I have so far...

int main()
{
   const int PEOPLE = 5, PRODUCTS = 6;
   double sales[ PEOPLE ][ PRODUCTS ] = { 0.0 }, value,
         totalSales, productSales[ PRODUCTS ] = { 0.0 };
   unsigned int salesPerson, product;
   fstream infile;

   infile.open("sales.txt");

   if (infile.bad())
    {
        cerr << "Unable to open file" << endl;
        exit (1);
    }

   for(int i = 0; i < PEOPLE ; i++)
   {
      for(int j = 0; j < PRODUCTS; j++ )
      {
         infile >> salesPerson >> product >> value;
         sales[ salesPerson ][ product ] += value;
      }

    }   

I am aware that the line infile >> salesPerson >> product >> value; is incorrect and causes the program to crash but do not know what to replace it with.

Thanks!

It will depend on how the file is layed out, but probably replace both lines 21 and 22 with this one line:

infile >> sales[i][j];

Post a few lines of the data file and we can be more specific about how to read it.

Sorry about that. Here is the format I will have the data file...

1 1 20.30

So I have

i j price

The first two values are int while the third needs to be double.

Oh, then I would read the file until end-of-file like this: Not that calling eof() is not necessary because the loop will stop when eof is reached.

int i,j;
float price;

while( infile >> i >> j >> price)
   sales[i][j] += price;

Thanks! That fixed it!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.