Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading data from file into array

Tags:

c++

I am trying to read specific data from a file into two 2D arrays. The first line of data defines the size of each array so when I fill the first Array i need to skip that line. After skipping the first line, the first array fills with data from the file until the 7th line in the file. The second array is filled with the rest of the data from the file.

Here's a labeled image of my data file: enter image description here

and here's my (flawed) code so far:

#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 the input everyone.

like image 832
darko Avatar asked Mar 08 '11 23:03

darko


People also ask

How do I read an array file?

Use the fs. readFileSync() method to read a text file into an array in JavaScript, e.g. const contents = readFileSync(filename, 'utf-8'). split('\n') . The method will return the contents of the file, which we can split on each newline character to get an array of strings.

How do you read a text file and store it to an array in Java?

In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method.

How do I read an array file in C++?

Use fstream to Read Text File Into 2-D Array in C++ To read our input text file into a 2-D array in C++, we will use the ifstream function. It will help us read the individual data using the extraction operator. Include the #include<fstream> standard library before using ifstream .


1 Answers

Your while loops iterate until the end of file, you don't need them.

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

Use instead (without the 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 seats.


Also you might want change arrays into vectors, since variable size arrays are hell.

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

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

like image 70
Tugrul Ates Avatar answered Sep 20 '22 17:09

Tugrul Ates