简体   繁体   English

std :: stringstream十六进制转换错误

[英]std::stringstream hex conversion error

I tried to do hex conversions using std::stringstream as the following: 我尝试使用std::stringstream进行十六进制转换,如下所示:

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

int i;

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

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

But it fails on subsequent conversions as the comment points out. 但是,正如评论指出的那样,它在随后的转换中失败了。 Do I need to reset the stringstream ? 我需要重置stringstream吗? Why does it fail? 为什么会失败?

You are performing formatted input and after extracting i out of the string-stream the eofbit is set. 您正在执行格式化输入,并在从字符串流中提取i后,设置了eofbit。 Hence you have to clear the state or all following formatted input/output will fail. 因此,您必须清除状态或所有后续格式化的输入/输出将失败。

#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;
}

If you check stream state after s << "10" , you will see the operation failed. 如果在s << "10"之后检查流状态,您将看到操作失败。 I don't know exactly why, but you can fix this problem by resetting the stream: 我不确切知道为什么,但您可以通过重置流来解决此问题:

#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 . 现场演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM