I am trying to read all of the integers from a file (can be up to 100 ints) into an array, and print out the numbers entered, and how many numbers were entered. I am having trouble with ".eof". No matter what I try, the last value in the input file is not read. Can somebody please tell me what the problem is? Here is the code.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int bubble[100];
int s = 0;
int count = 0;
string fileName;
//int i = 0;
for(int i = 0; i < 100; i++) bubble[i] = 0;
cout << "Enter the name of a file of integers to be sorted " << endl;
cin >> fileName;
ifstream myfile (fileName);
myfile >> s;
//bubble[0] = s;
while (! myfile.eof() ) //while the end of file is not reached
{
//myfile >> s;
for(int i = 0; i < 100; i++)
{
//myfile >> s;
if(! myfile.eof())
{
bubble[i] = s;
myfile >> s;
}
else
{
bubble[i] = -1;
}
}
//i++;
}
myfile.close();
for(int i = 0; i < 100; i++)
{
if(bubble[i] != -1)
{
count ++;
}
}
// cout << count;
for(int i = 0; i < count; i++)
{
if(bubble[i] != -1)
{
if((i % 10 == 9) || (i== count-1))
{
cout << setw(4) << bubble[i] << endl;
}
else
{
cout << setw(4) << bubble[i] << " ";
}
//count ++;
}
}
cout << "\n\nNumber of values in the input file: " << count << endl;
return 0;
}
input: 100 94 59 83 7 11 92 76 37 89 74 59 65 79 49 89 89 75 64 82 15 74 82 68 92 61 33 95 91 82 89 64 43 93 86 65 72 40 42 90 81 62 90 89 35 81 48 33 94 81 76 86 67 70 100 80 83 78 96 58
output: Enter the name of a file of integers to be sorted bubble_input.txt 100 94 59 83 7 11 92 76 37 89 74 59 65 79 49 89 89 75 64 82 15 74 82 68 92 61 33 95 91 82 89 64 43 93 86 65 72 40 42 90 81 62 90 89 35 81 48 33 94 81 76 86 67 70 100 80 83 78 96
Number of values in the input file: 59
(should be 60, and 58 should be in the last spot)
Thank you for any help!