Member Avatar for mhalls

Hi

I am trying to read a txt file into a 15x30 multi dimensional array. I am having a few problems with the code. This class is embedded within a class and the cout << seat[j] seems to work within the loops when I'm reading in the file.

When testing, I am taking random row and column numbers but the correct letter is not being returned. I'm guessing there must be a problem somewhere and the actual characters are not getting stored.


char seat[15][30];  /*stored as private data member of class  Auditorium*/

void Auditorium::readSeatsConfig(){
       ifstream fin;
       char next;
       fin.open("SeatsConfig.txt");
       if (fin.fail())
     {    cout << "Input file opening failed. Aborting\n";
           exit(1);
     } /*error checking*/  
      
     while (!fin.eof())
    {
        fin.get(next);
        for (int i=0; i<15;i++)  
           for (int j=0; j<30; j++) 
           {    
             seat[i][j]=next; 
             cout << seat[i][j];
             fin.get(next);
           }   /*for*/
    }/*while*/
}/*readSeatsConfig*/

Below is the driver program I am using to test the seat allocation, using the nested loop to retrieve all characters in the array.

char Auditorium::showSeat(){
     for (int i=0; i<15; i++)
     for (int j=0; j<30; j++)
     cout << "seat["<<i<<"]["<<j<<"] is" << seat [i][j];
     
     }/*showSeat*/

can anyone give me some idea on what's going wrong?

You have several potentual problems :

(a) If you have an extra character at the end of the file (e.g. '\n')
Since you test fin.eof ONLY at the start of each sequence you probably read the array then find that you are not at the end of the file , read ONE extra character and reset the whole array with junk.

Fix : Remove the while loop.

Better method: Read the whole array in one go:

fin.read(seat[0],15*30);
// Now test to see if you read enough characters...
if (fin.gcount()!=15*30)
   {
      // some error handling
  }

That will be a lot quicker as well.

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.