I have a simple test program (error checks removed):
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
int main() {
std::string line;
while(std::cin >> line) {
int value;
std::stringstream stream(line);
stream >> std::setbase(0) >> value;
std::cout << "You typed: " << value << std::endl;
}
}
Which works great for prefix-dependent integer parsing. It'll parse strings starting with "0x"
or "0X"
as hexadecimal and strings starting with '0'
as octal. This is explained in several resources that I use and have seen. What I haven't been able to find though, is an indication in the C++ standard that this is guaranteed to work.
Section 7.20.1.4.3 on strtol
in the C standard says (6.4.4.1 is the syntax for integer constants) I imagine the extraction operators use this under the hood:
If the value of base is zero, the expected form of the subject sequence is that of an integer constant as described in 6.4.4.1, optionally preceded by a plus or minus sign, but not including an integer suffix.
This works on the couple of versions of GCC that I've tried, but is it safe to use generally?