我可以说服operator>>
C++ 读取一个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;
}