Reading data from file to array

I am trying to read certain data from a file into two 2D arrays. The first row of data determines the size of each array, so when I fill the first array, I need to skip this row. After skipping the first line, the first array fills the data from the file to the 7th line in the file. The second array is filled with the remaining data from the file.

The image of my data file is marked here: enter image description here

and here is my (erroneous) code:

#include <fstream> #include <iostream> using namespace std; int main() { ifstream inFile; int FC_Row, FC_Col, EconRow, EconCol, seat; inFile.open("Airplane.txt"); inFile >> FC_Row >> FC_Col >> EconRow >> EconCol; int firstClass[FC_Row][FC_Col]; int economyClass[EconRow][EconCol]; // thanks junjanes for (int a = 0; a < FC_Row; a++) for (int b = 0; b < FC_Col; b++) inFile >> firstClass[a][b] ; for (int c = 0; c < EconRow; c++) for (int d = 0; d < EconCol; d++) inFile >> economyClass[c][d] ; system("PAUSE"); return EXIT_SUCCESS; } 

Thanks for putting everyone in.

+6
c ++
source share
3 answers

Your while loops repeat until the end of the file; you don't need them.

 while (inFile >> seat) // This reads until the end of the plane. 

Use instead (without while ):

 for (int a = 0; a < FC_Row; a++) // Read this amount of rows. for (int b = 0; b < FC_Col; b++) // Read this amount of columns. inFile >> firstClass[a][b] ; // Reading the next seat here. 

Apply the same for economic places.


You may also want to change arrays to vectors, since variable-sized arrays are hell.

 vector<vector<int> > firstClass(FC_Row, vector<int>(FC_Col)) ; vector<vector<int> > economyClass(EconRow, vector<int>(EconCol)) ; 

You need #include <vector> use vectors, their access is identical to arrays.

+3
source share

You need to reorder the for loops and read from the file:

 for (rows = 0; rows < total_rows; ++ rows) { for (col = 0; columns < total_columns; ++cols) { input_file >> Economy_Seats[row][column]; } } 

I will leave the EOF check and invalid input processing for the reader.

+2
source share

You read in seat once and then fill the array with this value. Then you read seat again and populate the entire array with this new value.

Try the following:

 int CurRow = 0; int CurCol = 0; while ( (inFile >> seat) && (CurRow < FC_Row)) { firstClass[CurRow][CurCol] = seat; ++CurCol; if (CurCol == FC_Col) { ++CurRow; CurCol = 0; } } if (CurRow != FC_Row) { // Didn't finish reading, inFile >> seat must have failed. } 

The second loop should use economyClass not firstClass

The reason for switching the cycle in this way is error handling, which is simplified when the cycle fails with an error. Alternatively, you can save for loops, use infile >> seat in the inner loop, but you will have to break out of two loops if reading failed.

+1
source share

All Articles