我可以说服 C++ 中的 operator>>
读取 hex
值 AND 和 decimal
值吗?下面的程序演示了读取十六进制是如何出错的。我希望相同的 istringstream
能够读取 hex
和 decimal
。
#include <iostream>
#include <sstream>
int main(int argc, char** argv)
{
int result = 0;
// std::istringstream is("5"); // this works
std::istringstream is("0x5"); // this fails
while ( is.good() ) {
if ( is.peek() != EOF )
is >> result;
else
break;
}
if ( is.fail() )
std::cout << "failed to read string" << std::endl;
else
std::cout << "successfully read string" << std::endl;
std::cout << "result: " << result << std::endl;
}
最佳答案
使用std::setbase(0)
启用依赖于前缀的解析。它将能够将 10
(dec)解析为十进制的 10,将 0x10
(hex)解析为十进制的 16,将 010
(八进制)解析为十进制的 8 .
#include <iomanip>
is >> std::setbase(0) >> result;
关于c++ - operator>> 可以读取 int hex AND decimal 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77266/