Can operator>> read an int hex AND decimal?
Asked Answered
P

3

6

Can I persuade operator>> in C++ to read both a hex value AND and a decimal value? The following program demonstrates how reading hex goes wrong. I'd like the same istringstream to be able to read both hex and 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;
}
Penurious answered 16/9, 2008 at 21:22 Comment(0)
D
12

Use std::setbase(0) which enables prefix dependent parsing. It will be able to parse 10 (dec) as 10 decimal, 0x10 (hex) as 16 decimal and 010 (octal) as 8 decimal.

#include <iomanip>
is >> std::setbase(0) >> result;
Dietrich answered 16/9, 2008 at 21:33 Comment(0)
D
12

You need to tell C++ what your base is going to be.

Want to parse a hex number? Change your "is >> result" line to:

is >> std::hex >> result;

Putting a std::dec indicates decimal numbers, std::oct indicates octal.

Dicentra answered 16/9, 2008 at 21:33 Comment(0)
D
12

Use std::setbase(0) which enables prefix dependent parsing. It will be able to parse 10 (dec) as 10 decimal, 0x10 (hex) as 16 decimal and 010 (octal) as 8 decimal.

#include <iomanip>
is >> std::setbase(0) >> result;
Dietrich answered 16/9, 2008 at 21:33 Comment(0)
S
-2

0x is C/C++ specific prefix. A hex number is just digits like a decimal one. You'll need to check for presence of those characters then parse appropriately.

Septempartite answered 16/9, 2008 at 21:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.