-1

When I'm reading from a file it adds one space at the end. So after, when I need to sort the string, it sorts the extra space too. And is added to the output file.

int main()
{
    int siz=1000000;
    char a[siz];

    ifstream readfile("AllAlpha.txt");
    ofstream outfile("sorted.txt");

    if(!readfile)
    {
        cout << "An error occurred while opening the input data stream file \"AllAlpha.txt\"!" << endl;
        return 1;
    }
    // read file
    int i=0;
    while (!readfile.eof())
    {
        readfile.get(a[i]);
        i++;
    }
    int size=i;

    // sort the array
    //quicksort(a, 0, size-1);

    // output sorted array to file
    for (int num=0;num<size;num++)
    {
        outfile<<a[num];
    }
    return 0;
}
  • 2
    [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – πάντα ῥεῖ Oct 14 '15 at 20:37

2 Answers2

1

By using:

readfile.get(a[i]);
i++;

You are assuming that readfile.get(a[i]) was successful. That is not true after you have read the last character of the file.

Change your loop to:

char c;
while (readfile.get(c))
{
   a[i] = c;
   ++i;
}
R Sahu
  • 196,807
  • 13
  • 136
  • 247
0

This may be a perfect example of why using readfile.eof () in a while condition is almost always wrong: the eof flag is only set once the end of the file is actually read. So in this case, the end of the file is read and assigned to a[i] then iostream::eof is set, and only then does program execution continue beyond the while loop.

cowdrool
  • 304
  • 1
  • 6
  • so simply cutting the last element from the read array would tehnically get rid of the extra space? –  Oct 14 '15 at 21:00