Well, I tried that code, but it doesn't compile as written. I'm not sure about the infinite loop, but most likely the input file was not opened successfully.
There are a few things wrong with the code. When accessing the values in an array, you need to supply a subscript, for example
inputFile >> numbers[0]
rather than just
inputFile >> numbers
.
Also, testing for
eof()
is generally a poor idea. The file access may fail for many reasons other than end of file, for example there may be non-numeric data, or (as you perhaps discovered) the file might not even be open.
So here's some code to read the numbers into an array. After that has completed, the contents of the array are displayed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#include <iostream>
#include <fstream>
using namespace std;
const int MAX = 50;
int numbers[MAX];
int main()
{
ifstream inputFile;
inputFile.open("numbers.txt");
if (!inputFile.is_open())
{
cout << "inputFile is not open" << endl;
return 1;
}
int n = 0; // Count the numbers as we read them in
while (n<MAX && inputFile >> numbers[n])
{
n++;
};
// Output the numbers
for (int i=0; i<n; i++)
{
cout << i << " " << numbers[i] << endl;
}
return 0;
}
|
The one line which may look a little tricky is line 23
while (n<MAX && inputFile >> numbers[n])
Here the while condition is testing two separate things. First, that the subscript
n
is within the size of the array, and then it tries to read an integer and checks whether it was successful. If all was well, n is increased by 1 and the loop is repeated.