[英]std::stringstream hex conversion error
我尝试使用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;
}
如果在s << "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';
}
现场演示 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.