简体   繁体   中英

std::stringstream hex conversion error

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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