Pedro d'Aquino
Pedro d'Aquino

Reputation: 5220

Why does istream_iterator<unsigned char, unsigned char> throw std::bad_cast?

What is going on?

#include <iostream>
#include <iterator>
#include <sstream>

int main() {
    std::basic_stringbuf<unsigned char> buf;
    std::basic_istream<unsigned char> stream(&buf);
    // the next line throws std::bad_cast on g++ 4.4
    std::istream_iterator<unsigned char, unsigned char> it(stream);
}

I've tried stream.write(some_array, sizeof(some_array) before constructing the iterator, to no avail.

Thanks.

Upvotes: 2

Views: 1191

Answers (2)

Cubbi
Cubbi

Reputation: 47408

It throws from sentry object's constructor where it checks the ctype facet on the stream (it needs it so it can skip whitespace), which happens to be NULL because it's not defined for unsigned chars.

Do you need to handle whitespace on that stream? If not, change to

std::istreambuf_iterator<unsigned char> it(stream);

Upvotes: 2

scigor
scigor

Reputation: 1617

shouldnt it be:

std::istream_iterator<unsigned char> it(stream);

Upvotes: 0

Related Questions