2

我在使用 gcc4.4 的 Ubuntu 10.04 中遇到了同样的问题,相同的代码在使用 gcc4.1 的 RH 5.5 上运行良好

#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 中得到纠正,不确定是否该错过的行为(除非我遗漏了某些东西)与相同的问题有关。

4

1 回答 1

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 无符号转换损坏?.

于 2010-08-04T15:41:22.177 回答