我可以说服C++中的operator >>同时读取十六进制值AND和十进制值吗?以下程序演示了如何读取十六进制错误.我想要相同的istringstream能够读取十六进制和十进制.
#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;
}
Run Code Online (Sandbox Code Playgroud)
nsa*_*ers 12
你需要告诉C++你的基础是什么.
想要解析十六进制数?将您的"是>>结果"行更改为:
is >> std::hex >> result;
Run Code Online (Sandbox Code Playgroud)
将std :: dec表示十进制数,std :: oct表示八进制数.
use*_*392 10
使用std::setbase(0)
它启用前缀相关的解析.它将能够解析10
(dec)为10十进制,0x10
(十六进制)为16十进制,010
(八进制)为8十进制.
#include <iomanip>
is >> std::setbase(0) >> result;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2268 次 |
最近记录: |