vendredi 28 octobre 2016

Why does std::ios_base::ignore() set the EOF bit?

When I read all data from a stream, but make no attempt to read past its end, the stream's EOF is not set. That's how C++ streams work, right? It's the reason this works:

#include <sstream>
#include <cassert>

char buf[255];

int main()
{
    std::stringstream ss("abcdef");
    ss.read(buf, 6);

    assert(!ss.eof());
    assert(ss.tellg() == 6);
}

However, if instead of read()ing data I ignore() it, EOF is set:

#include <sstream>
#include <cassert>

int main()
{
    std::stringstream ss("abcdef");
    ss.ignore(6);

    assert(!ss.eof());        // <-- FAILS
    assert(ss.tellg() == 6);  // <-- FAILS
}

On GCC 4.8 and GCC trunk (Coliru), this has the unfortunate side-effect of making tellg() return -1, which is annoying for what I'm doing.

Is this standard-mandated? If so, which passage and why? Why would ignore() attempt to read more than I told it to?

I can't find any reason for this behaviour on cppreference's ignore() page.

Aucun commentaire:

Enregistrer un commentaire