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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With