Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read data file into an array

I am trying to read a text file and store it in an array, but my program keeps getting stuck in an infinite loop.

Here is my code:

int main () {
    const int size = 10000; //s = array size
    int ID[size];
    int count = 0; //loop counter
    ifstream employees;

    employees.open("Employees.txt");
    while(count < size && employees >> ID[count]) {
        count++;
    }

    employees.close(); //close the file 

    for(count = 0; count < size; count++) { // to display the array 
        cout << ID[count] << " ";
    }
    cout << endl;
}
like image 420
Lina Hossam El-deen Avatar asked Jun 11 '26 05:06

Lina Hossam El-deen


1 Answers

First, you should use a std::vector<int> ID; instead of a raw int array.

Secondly, your loop should look more like this:

std:string line;
while(std::getline(employees, line)) //read a line from the file
{
    ID.push_back(atoi(line.c_str()));  //add line read to vector by converting to int
}

EDIT:

Your problem in the above code is this:

for(count = 0; count < size; count++) { 

You're reusing your count variable that you used earlier to keep count of the number of items you read from your file.

It should be something like this:

for (int x = 0;  x < count; x++) {
   std::cout << ID[x] << " ";
}

Here you're using your count variable to print the number of items read from the file.

like image 120
Tony The Lion Avatar answered Jun 13 '26 07:06

Tony The Lion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!