views:

47

answers:

2

I'm having same issue in Ubuntu 10.04 using gcc4.4, the same code works fine on RH 5.5 using gcc4.1

#include <sstream>
#include <iostream>

int main(int argc, char** argv) {

  std::stringstream myStream;
  myStream << "-123";

  unsigned int myUInt;
  myStream >> myUInt;

  if(myStream.fail()) {
    std::cout << "FAILED" << std::endl;
  }
} 

doesn't give FAILED, I have already found this:

http://gcc.gnu.org/bugzilla/show_bug.cgi?id=39802

where it stated that it was corrected in gcc4.1, not sure the if that miss behave (unless I'm missing something) is related to same problem.

A: 

Yes it does.
See here

the_drow
What operating system are you using?On my platform doesn't fail:$ cat /etc/issueUbuntu 10.04.1 LTS \n \l$ g++ --versiong++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3and /usr/lib/libstdc++.so.6 points to libstdc++.so.6.0.13
Gaetano Mendola
Why the downvote?It's codepad and it uses gcc and linux.
the_drow
@the_drow post your code inline
Sam Miller
@Sam Miller: The reason I posted this on codepad is that codepad compiles the exact same code and outputs failed
the_drow
+1  A: 

I'm not sure why you are expecting it to fail. sscanf() also doesn't fail, but reads the the number, and the C++ streams are supposed to work like the scanf functions:

#include <stdio.h>

int main(int argc, char** argv) {
    unsigned int n;
    if ( ! sscanf( "-1", "%ud", & n ) ) {
        printf( "fail\n" );
    }
    else {
        printf( "%ud", n );
    }
} 

prints 4294967295d.

And see also http://stackoverflow.com/questions/786951/stringstream-unsigned-conversion-broken.

anon
Because on RH5.4 with 4.1 compiler it fails. Also I'm not sure about the fact that stringstream has to behave like scanf. Not to mention the fact that boost::lexical_cast relies on the fact that it has to fail, indeed I discovered the stringstream not failing due the fact that boost::lexical_cast<unsigned int>("-123") is not throwing.The link you posted states at the end that it will be fixed for 4.4.1 but actualy that code fails with 4.4.3
Gaetano Mendola
@kalman Yes, that's the bug! It was in 4.1, and was fixed later. also, you can see from the other question that there is some debate about what the "correct2 behaviour is.
anon
So you mean the fact stringstream fails in streaming "-123" in an unsigned type it was a bug and not a feature?
Gaetano Mendola
@kalman Do you expect if you read -1 into an unsigned int, it takes on the value UINT_MAX? If so, current behaviour (i.e. not failing) is correct.
anon
No I expect same behave as I'm converting "XXXXXX" in an int.
Gaetano Mendola
@kalman Well, I think you are out of luck then.
anon
Indeed I'm out of luck. Anyway, now I check with a type traits if the target type is an unsigned and then before to convert to the real target I convert it first to a double to check if it's negative and in case I throw a bad_cast....
Gaetano Mendola