【问题标题】:std::stringstream hex conversion errorstd::stringstream 十六进制转换错误
【发布时间】:2014-04-23 09:54:00
【问题描述】:

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

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

int i;

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

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

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

【问题讨论】:

  • 它究竟是如何“失败”的?
  • @Singer:从字面上看,流进入fail 状态;-)
  • 可能重复:stackoverflow.com/q/13891856/187543 在发布问题之前我没有搜索过。

标签: c++ stl hex stringstream data-conversion


【解决方案1】:

您正在执行格式化输入,从字符串流中提取 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;
}

【讨论】:

    【解决方案2】:

    如果您在s &lt;&lt; "10" 之后检查流状态,您将看到操作失败。我不知道具体原因,但您可以通过重置流来解决此问题:

    #include <iostream>
    #include <sstream>
    
    int main()
    {
      std::stringstream s;
      s << std::hex;
    
      int i;
    
      s << "100";
      s >> i;     // 256
    
      std::cout << i << '\n';
    
      s.str("");
      s.clear(); // might not be necessary if you check stream state above before and after extraction
    
      s << "10";  // doesn't work
      s >> i;
    
      std::cout << i << '\n';
    }
    

    Live demo here.

    【讨论】:

    • 似乎有必要在提取某些内容后立即使用s.clear() 才能再次使用字符串流。
    • 啊,是的,听起来合乎逻辑。我没有想清楚:-)
    猜你喜欢
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 2016-01-08
    • 2017-08-29
    • 2015-12-12
    • 2013-10-22
    • 2011-08-24
    • 1970-01-01
    相关资源
    最近更新 更多