c++ - stringstream 在无符号类型中失败 "streaming"负值?

标签 c++ std stringstream

我在使用 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;
  }
} 

不给FAILED,这个我已经找到了:

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

其中声明在 gcc4.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? .

关于c++ - stringstream 在无符号类型中失败 "streaming"负值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3407100/

相关文章:

python - 使用Python中的自定义比较函数对字典键对象列表进行排序

C++ 使用 STD 解析 XML

c++ - 使用 stringstream 将 pid_t 转换为 const char*

c++ - const char * 对 vector<unsigned char> 的初始化

C++ libdl.so : Can't open shared library in 32bit application

c++ - 检查实现了哪些基类

c++ - 为什么 unique_ptr<T>::~unique_ptr 需要 T 的定义?

c++ - 随机化 std::list 时提高性能

c++ - 如何将部分流作为参数传递?

c++ - 在 stringstream 的 ssh 命令中转义 bash 脚本中的引号