4

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.

balki
  • 26,394
  • 30
  • 105
  • 151
  • [`strtol`](http://en.cppreference.com/w/cpp/string/byte/strtol) should do that. So should [`stoi`](http://en.cppreference.com/w/cpp/string/basic_string/stol). – chris Oct 31 '12 at 07:21

2 Answers2

8

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

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Yes, it's a nice C++ wrapper for `strtol`. – Dmytro Sirenko Oct 31 '12 at 07:23
  • @EarlGray: Wrapper? Who said? (+1 BTW) – Nawaz Oct 31 '12 at 07:25
  • @EarlGray, Apart from working when only the first half of the input is valid, it's ok. I don't know if Boost's lexical cast includes these prefixes, but that's a nice option. – chris Oct 31 '12 at 07:25
  • @Nawaz the name suggests some similarity to `strtol/strtoi/strtof`, and the function signature looks like `strtol` with `const char *` replaced by `std::string` – Dmytro Sirenko Oct 31 '12 at 07:30
  • 1
    @EarlGray It *could* use C functions under the hood, but the standard doesn't specify this. I doubt it would be the preferred choice of implementations either. – juanchopanza Oct 31 '12 at 07:43
  • @balki I am not sure what supporting base 0 would entail. The implementation I am using seems to try to figure out the base from the input if base 0 is specified. – juanchopanza Oct 31 '12 at 10:27
  • 1
    @juanchopanza - `stol` etc. were designed to look like `strtol` etc. precisely so they could be implemented by calling the C functions. There's no good reason to rewrite that parsing code. – Pete Becker Oct 31 '12 at 11:09
3

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

Dmytro Sirenko
  • 5,003
  • 21
  • 26
  • It still needs the third argument to specify the base. – balki Oct 31 '12 at 07:25
  • 1
    @balki Just set it to zero, the function will figure out what to use: decimal/octal/hexadecimal numbers. The third argument is useful for some strange bases or when `0x` prefix is omitted. – Dmytro Sirenko Oct 31 '12 at 07:27