0

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!

leppie
  • 109,129
  • 16
  • 185
  • 292
Zach
  • 65
  • 1
  • 8

1 Answers1

1

What you do in your code is (excuse the pseudo-pseudo code):

save value of `s` in `bubble[i]`
read in an integer, saving it in the variable `s`,
repeat as long as we have something on the input

This way when you reach end of file, the last variable is still only stored in s, you don't copy it over to bubble[i]. Simply save it in the array straight away, should solve your problem.

Edit - what I also noticed - the while loop doesn't work like an if. If the file has more than 100 integers, you will overwrite the first 100 with the numbers that follow (and possibly -1s).

Kelm
  • 939
  • 5
  • 14