c++ - operator>> 可以读取 int hex AND decimal 吗?

标签 c++ hex istringstream

我可以说服 C++ 中的 operator>> 读取 hex 值 AND 和 decimal 值吗?下面的程序演示了读取十六进制是如何出错的。我希望相同的 istringstream 能够读取 hexdecimal

#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/

相关文章:

c++ - 在 C++ 中转储十六进制 float

c - 以下每个项目都有一个错误(我需要修复它们)

c++ - 如何将 ifstream 转换为 istringstream

c++ - 编译器不会使用复制分配来代替移动?

c++ - 调用删除时的总线错误 (C++)

c++ - 两个具有成员函数的类从另一个类获取指向对象的指针

c++ - istringstream 的五倍输出

c++ - 具有调用者上下文的模板函数?

string - 如何在scala中将长十六进制字符串转换为BigInt

C++ - 我如何误用 istringstream 忽略?