-
Number representation
Hello.
I would like to put a question maybe someone could help me. I wanna create a c++ application that get's a number as a argument and does stuff with it.
Using other commandline application's I observed that most application interpret a number writen like 10 as 10 in decimal and a number as 0x10 or 0X10 as 16 in decimal/ 10 in hex.
I would like to ask if somebody do know about a library function that convert's a string, representing a number into a numerig value, taking care of the common numbering representations. I search for something like atoi() or sscanf(s,"%d") but where I don't have to specify if the string is representing a hex number or dec number :).
Do you also know some document where the different numbering representation for command line application's are described ?
Thanks for your time
-
strtol() and sscanf("%i") both treat strings in the following way
Begins with 0x, it's hex
Begins with 0, it's octal
Begins with 1..9, it's decimal
-
edit: on second thought I probably misread your question but I'll share this anyway
Code:
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string num("100");
std::istringstream iss_dec(num);
std::istringstream iss_hex(num);
std::istringstream iss_oct(num);
int dec;
iss_dec >> std::dec >> dec;
int hex;
iss_hex >> std::hex >> hex;
int oct;
iss_oct >> std::oct >> oct;
std::cout << num << " interpreted as decimal: " << dec << std::endl;
std::cout << num << " interpreted as hexidecimal: " << hex << std::endl;
std::cout << num << " interpreted as octal: " << oct << std::endl;
return 0;
}
-
Thank you.
sscanf("%i") is what I was searching.
Also the conversions using C++ methods where helpfull too. I didn't knew them till now :)