-->

GCC 4.7的IStream ::所以tellg()返回-1达到EOF后,(GCC 4.7 ist

2019-07-04 15:05发布

下面的代码工作用gcc 4.4。
但是GCC 4.7会给断言失败。

#include <assert.h>
#include <iostream>
#include <sstream>

using namespace std;

int main()
{

    string input("abcdefg");
    stringstream iss(input);
    ostringstream oss;
    oss << iss.rdbuf();

    assert (!iss.eof());
    (void) iss.peek();
    assert (iss.eof());

    // the following assertion will fail with gcc 4.7
    assert( streamoff(iss.tellg()) ==
            streamoff(input.length()) );

    return 0;
}

在GCC 4.7,如果istream的已经达到EOF,所以tellg()将返回-1。 没有pubseekoff()也不seekoff()将被称为在GCC 4.4它是没有问题的。

这是应该的行为,GCC 4.4或4.7的gcc? 为什么?

Answer 1:

据C ++ 11部分27.7.2.3p40,

如果fail() != false ,返回pos_type(-1)

所以,GCC 4.7对C ++的当前版本的正确的行为(假设peek()在流导致最终failbit被设置,并且哨兵施工期间这样做,因为skipws是默认设置)。

纵观C ++ 03的措辞,这是一样的。 27.6.1.3p37。 所以,你在GCC 4.4描述的行为是一个错误。



Answer 2:

准确地说, eofbit不会造成tellg()返回-1 。 但是,你读过去 EOF事实设置failbit ,和tellg()将返回-1如果badbitfailbit设置。

解决的办法是在调用之前清除状态标志tellg()

iss.clear();
iss.tellg();  // should work


文章来源: GCC 4.7 istream::tellg() returns -1 after reaching EOF
标签: c++ istream