I’m trying to read a file that has this format:
1
2
3
4
I’m trying to store these values into an array using a while
loop:
ifstream myfile("file.dat");
int n, i;
int myarray[30];
if (!myfile) {cerr << "File not Found!" << endl;}
i = 0;
while (true) {
if (myfile.eof()) {break;}
myfile >> n;
myarray[i] = n;
cout << myarray[i] << endl;
i++;
}
When I execute the program, the result from cout
is
1
2
3
4
4
It seems like the program is executing the last iteration of the while
loop a second time. But why? I have a break
statement in it that should exit out of the loop once end of file is reached. Is the break
statement not appropriate for this?
1