balki
balki

Reputation: 27664

How to convert string to int with different bases?

I want to convert string to int but the conversion has to consider the prefixes 0x or 0 if any and consider the input as hex or oct respectively. Using istringstream, you need to explicitly specify the base. Is there any way than explicitly coding to check for characters 0x?

Edit: The conversion should implicitly find the base based on the prefix. Just like int i = 0x123; does.

Upvotes: 4

Views: 3063

Answers (2)

Dmytro Sirenko
Dmytro Sirenko

Reputation: 5083

You can use C function strtol : http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/ It understands 0x/0 prefices.

Upvotes: 3

juanchopanza
juanchopanza

Reputation: 227390

You can use the std::stoi family of functions from C++11.

Upvotes: 8

Related Questions