Can the >> operator read int hex and decimal?

Is it possible to convince the operator → in C ++ to read both the hexadecimal value of AND and the decimal value? The following program demonstrates how reading hexadecimal code does not work correctly. I would like the same istringstream to be able to read both hexadecimal and decimal numbers.

#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;
}
+3
source share
3 answers

Use std::setbase(0)which allows you to use prefix-dependent parsing. He will be able to parse 10(dec) as 10 decimal places, 0x10(hex) as 16 decimal places and 010(octal) as 8 decimal places.

#include <iomanip>
is >> std::setbase(0) >> result;
+9
source

You need to tell C ++ what your base will be.

? " → " :

is >> std::hex >> result;

std:: dec , std:: oct .

+12

0x is a special C / C ++ prefix. A hexadecimal number is just numbers, like decimal. You will need to check for these characters and then analyze them accordingly.

-2
source

Source: https://habr.com/ru/post/1696998/


All Articles