Another problem with istringstream

Benjamin Kosnik bkoz@cygnus.com
Sat Apr 1 00:00:00 GMT 2000


#include <iostream>
#include <string>
#include <sstream>
int main()
{
    string s = "123";
    istringstream is(s);
    int i, j;
    if (is >> i >> j) 
      cout << "ok" << endl;
}

> outputs "ok" but actually it shouldn't, because ">> j" fails and j
> gets garbage.

    if (is >> i >> j) 

Is true. This is not a bug. Here's why:

istream::operator>>int
istream::operator>>int
basic_ios::operator void*()

This last call checks, as per the standard:

      operator void*() const 
      { return this->fail() ? 0 : const_cast<basic_ios*>(this); }

Translation: it's only looking for failbit or badbit. Neither are set
(eofbit, is, but that isn't being checked. . .) so yes, "ok" gets printed.

Try checking for is.good()

-benjamin



More information about the Libstdc++ mailing list