使用istream :: peek()将下一个值与当前值进行比较

时间:2015-07-02 00:52:15

标签: c++ comparison mergesort istream peek

当下一个值为50时,为什么peek()的条件没有返回FALSE?

当我的代码从文件读取40并且比较50是否小于40时,它返回TRUE。这显然是错误的并且按照子文件中的数字的顺序创建了一个错误。

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;
        }
    }

我输入了一个temp int来告诉我fin_dataFile.peek()返回的是什么,我一直得到32.这是一个空格的ascii值。有道理,因为每个数字都是空格分隔的。我尝试使用:

来解决这个问题
if ((fin_dataFile >> std::ws).peek() < value)

但是peek()仍然返回与文本文件不同的数字。

背景

我正在进行外部自然合并。我的分割功能没有正确分割数据。它应该读取空格分隔数字的文件,并将它们分成子排序数据的两个子文件。 它会这样做,但顺序不正确。

我的算法通过使用peek()将主文件中的下一个数字与已读入的当前数字进行比较来划分文件之间的数字。

这是要拆分的数据的示例文本文件:

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

1 个答案:

答案 0 :(得分:3)

peek()向前查看文件中的下一个字符

在您的情况下,“40”之后的文件中的下一个字符是空格字符,ASCII空格或32,小于40。