When using scanf() and its variants, the format specifier %i
will accept data as hex (prefixed "0x"), octal (prefixed "0"), or decimal (no prefix), so for example the strings "0x10", "020", and "16" are all converted to an integer with decimal value 16.
Can this be done with std::istream::operator>>
formatted input?
Using plain >> i
with no i/o manipulator "0x10" is converted to zero (or rather the leading 0 is, the "x10" part is not processed), and "020" to 20. The hex
, oct
and dec
manipulators behave like %x
, %o
and %d
respectively. I am looking for a general integer input manipulator that works like %i
.
Interestingly perhaps the hex
manipulator accepts both "0x10" and "10" converting either to 16 decimal.
In case you might be wondering, I am implementing an expression evaluator, and I would like allowed integer operands to be hex, octal, or decimal using the C/C++ prefix convention. The current implementation using sscanf()
does this automatically using %i
, and I am curious as to whether this could be modified to use iostream without having to explicitly parse the numeric format.
std::ios_base& integer( std::ios_base& str );
– Nadaba