我尝试使用 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/