I tried to do hex conversions using std::stringstream as the following:

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? Why does it fail?

有帮助吗?

解决方案

You are performing formatted input and after extracting i out of the string-stream the eofbit is set. 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. 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归因
不隶属于 StackOverflow
scroll top