stringstream无法在无符号类型中“流式传输”负值?

时间:2010-08-04 15:27:20

标签: c++ std stringstream

我在使用gcc4.4的Ubuntu 10.04中遇到同样的问题,相同的代码可以正常工作 在RH 5.5上使用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;
  }
} 

没有给出失败,我已经发现了这个:

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

它表示已在gcc4.1中更正,而不是 确定是否表现出错(除非我遗漏了什么) 与此问题有关。

1 个答案:

答案 0 :(得分:1)

我不确定你为什么期望它失败。 sscanf()也不会失败,但读取数字,C ++流应该像scanf函数一样工作:

#include <stdio.h>

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

打印4294967295d。

另见stringstream unsigned conversion broken?