Tutorial :stringstream fails “streaming” negative values in unsigned types?



Question:

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.


Solution:1

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 stringstream unsigned conversion broken?.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »