0

My program is all running fine except that it is reading a seemingly random seven-digit number at the end of the file to add an additional number to the file and I have not been able to figure out why. I was able to determine that it has something to do with the first while() loop.

I have tried everything I can think of and one thing I have noticed is that when I change the global variable to the number of numbers I know are in the file (12) it will work perfectly. However, I am suppose to do this so that I do not know exactly how many numbers are in the file.

What the output in the new file is suppose to look like but with the extra number: 8 10 12 17 25 36 47 62 62 65 87 89 2972880 //However this last seven digit number is not suppose to be there...here is the code...

#include <iostream>
#include <fstream>

using namespace std;

const int SIZE = 256;

int main(void)
{
    int getNumbers[SIZE];
    ofstream outFile;
    ifstream inFile;
    bool success;
    int count = 0,
        total = 0,
        add = 1;
    int num;

    inFile.open("numbers.txt");

    if (inFile.is_open())
    {
        cout << "File successfully read." << endl;
    }

    while (count < (total + add) && !inFile.eof())
    {
        inFile >> getNumbers[count];
        total += add;
        count++;
    }

    int grandTotal = (total - 1);

    do
    {
        success = false;
        for (int i = 0; i < grandTotal; i++)
        {
            if (getNumbers[i] > getNumbers[i + 1])
            {
                num = getNumbers[i];
                getNumbers[i] = getNumbers[i + 1];
                getNumbers[i + 1] = num;
                success = true;
            }
        }
        grandTotal--;

    } while (success);

    inFile.close();

    outFile.open("sorted.txt");

    if (outFile.is_open())
    {
        cout << "File successfully opened." << endl;
    }

    int index = 0;
    while (index < total)
    {
        outFile << getNumbers[index]
                << " \n";
        index++;
    }

    outFile.close();

    return 0;
}
bigZigZag
  • 33
  • 5
  • 2
    https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Galik Dec 15 '14 at 21:42
  • Apparently you "know" there are no more than 256 numbers. Unrelated, but put a cap on that read loop. And `add` seems somewhat useless in this code, as it is simply `1`. Maybe [something like this](http://pastebin.com/XwHs24zH) – WhozCraig Dec 15 '14 at 21:57

1 Answers1

0

As @Galik pointed out, you shouldn't check for eof() in a loop condition, because it will always give you one garbage data point at the end. Move the read into the loop condition.

while (count < (total + add) && inFile >> getNumbers[count]) 
{
    total += add;
    count++;
}
Ryan Bemrose
  • 9,018
  • 1
  • 41
  • 54