Search code examples
c++comparisonmergesortistreampeek

Using istream::peek() to compare next value against current value


Why is my condition with peek() not returning FALSE when the next value is 50?

When my code has read in 40 from a file and compares if 50 is less than 40, it returns TRUE.This is obviously wrong and creating a bug in the order the numbers in my sub files appear.

while (fin_dataFile >> value) //fin_dataFile is type ifstream reading the original data
    {
        // write the int stored in value to the second sub file
        // fout_splitFile2 is type ofstream
        fout_splitFile2 << value << " ";

        // if the next value in the original data set is less than the current value
        // that was read, break the loop so we can read in that next value to store it
        // in the first sub file instead 
        if (fin_dataFile.peek() < value)
        {
            break;
        }
    }

I put in a temp int to tell me what fin_dataFile.peek() was returning and I kept getting 32. This is the ascii value for a space. Makes sense because each number is space separated. I tried working around this by using:

if ((fin_dataFile >> std::ws).peek() < value)

But then peek() was still returning different numbers than in the text file.

Background:

I'm working on an external natural mergesort. My split function is not splitting the data correctly. It should read in a file of space separated numbers and split them into two sub files of sub sorted data. It does so, but not in the proper order.

My algorithm divides the numbers between files by comparing the next number in the main file using peek() with the current number that has been read in.

This is a sample text file of data to be split:

75 55 15 20 85 30 35 10 60 40 50 25 45 80 70 65

Solution

  • peek() peeks ahead at the next character in the file.

    In your case, the next character in the file after "40" is a space character, ASCII space, or 32, which is less than 40.