c++ - std::stringstream 十六进制转换错误

标签 c++ stl hex stringstream data-conversion

我尝试使用 std::stringstream 进行十六进制转换,如下所示:

std::stringstream s;
s << std::hex;

int i;

s << "100";
s >> i;     // 256

s << "10";  // doesn't work
s >> i;

但是正如评论指出的那样,它在后续转换中失败了。我需要重置 stringstream 吗?为什么会失败?

最佳答案

您正在执行格式化输入,并且在从字符串流中提取 i 后设置了 eofbit。因此,您必须清除状态,否则所有后续格式化输入/输出都将失败。

#include <sstream>
#include <iostream>

int main()
{
    std::stringstream s;
    s << std::hex;

    int i;

    s << "100";
    s >> i;     // 256
    std::cout << i << '\n';
    s.clear();  // clear the eofbit
    s << "10";  
    s >> i;     // 16
    std::cout << i << '\n';
    return 0;
}

关于c++ - std::stringstream 十六进制转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23240815/

相关文章:

java - 如何在 Clojure 中直接使用位?

java - 比较带符号的十六进制数

c++ - 虚成员函数定义可以出现在类模板之外吗?

c++ - boost::filesystem::path::append(通过迭代器)导致编译器错误

c++ - 正确的 QueryPerformanceCounter 函数实现/时间每次都改变

c++ - gcc reverse_iterator 比较运算符丢失了吗?

c++ - 修改 std::map 的 key

c++ - 如何将 QString 复制到 wchar_t 缓冲区

c++ - C++ STL Map 在创建后是否会移动值的位置?

string - BITS 数据类型的十六进制字符串表示是什么?