Am I filling this array incorrectly or throwing it wrong?

I am working on a program that populates an array with data from a text file. When I output the array, its contents are not in the order in which I thought I was reading them. I think the problem is either in one of the for loops that inject data into the array or output the array to iostream. Can anyone spot my mistake?

Data :

(I changed the first number in each line to 2-31 to distinguish it from 0 and 1) enter image description here

Output :

enter image description here

Code :

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

using namespace std;

int main()
{
    ifstream inFile;
    int FC_Row, FC_Col, EconRow, EconCol, seat, a, b;

    inFile.open("Airplane.txt");

    inFile >> FC_Row >> FC_Col >> EconRow >> EconCol;

    int airplane[100][6];

    int CurRow = 0;
    int CurCol = 0;

    while ( (inFile >> seat) && (CurRow < FC_Row)) 
    {
     airplane[CurRow][CurCol] = seat;
     ++CurCol;
      if (CurCol == FC_Col)
       {
       ++CurRow;
       CurCol = 0;
       }
    }


while ( (inFile >> seat) && (CurRow < EconRow)) 
{
 airplane[CurRow][CurCol] = seat;
 ++CurCol;
  if (CurCol == EconCol)
    {
     ++CurRow;
     CurCol = 0;
    }
 }

    cout << setw(11)<< "A" << setw(6) << "B"
    << setw(6) << "C" << setw(6) << "D"
    << setw(6) << "E" << setw(6) << "F" << endl;
    cout << " " << endl;

    cout << setw(21) << "First Class" << endl;
    for (a = 0; a < FC_Row; a++)
    {
        cout << "Row " << setw(2) << a + 1;
        for (b = 0; b < FC_Col; b++)
        cout << setw(5) << airplane[a][b] << " ";

        cout << endl;
    }

    cout << setw(23) << "Economy Class" << endl;
    for (a = 6; a < EconRow; a++)
    {
        cout <<"Row " << setw(2)<< a + 1;
        for (b = 0; b < EconCol; b++)
        cout << setw(5) << airplane[a][b] << " ";

        cout << endl;
    }


    system("PAUSE");
    return EXIT_SUCCESS;
}
+3
source share
4 answers

You are filling this out incorrectly.

for (a = 0; a < 100; a++)    
    for (b = 0; b < 6; b++)

The above loop doesn’t work well with the first lines of your file, in which you do not have 6 elements per line.

2, 1, 1, 1, 3, 0 [0].

EDIT: .

for (a = 0; a < FC_Row; a++)    
    for (b = 0; b < FC_Col; b++)
        inFile >> airplane[a][b] ;

for (a = 0; a < EconRow; a++)    
    for (b = 0; b < EconCol; b++)
        inFile >> airplane[a+FC_Row][b] ;
+1

, :

   for (a = 0; a < 100; a++)    
        for (b = 0; b < 6; b++)
            inFile >> airplane[a][b] ;

, 6 , , 6 4 .

+1

100x6, 4 .

- - :

 for (a = 0; a < 100; a++)    
        for (b = 0; b < 6; b++)
        {
          char c;
          inFile>>c;
          if (c is new line){
            break;
          }

          //fill in the 2d array
        }
0

, std:: getline. , , , , 2- .

, , , .

, , EconRow EconCol, .

, .

0

All Articles