Char to int

Hello,
I just want to know if there is any function which convert char to int (for example '1' will be converted to 1) and throw and exception if char is not a number (for exaple if char is 'p' it will throw an exception).
Last edited on
Such a function is a pretty simple thing you can write yourself. Here's one:

1
2
3
4
5
6
7
8
int char_to_int (char input)
{
    if ( input >= '0'  &&  input  <= '9')
    {
      return input - 48;
    }
    throw std::exception();
}


Prefer subtracting the character '0'. Not only does it remove the magic number 48, it also eliminates reliance on ASCII-compatible encodings.

Another assumption (i.e., the contiguity of 0-9) is guaranteed by the standard.
But subtracting 48 makes you look like a wizard to people who don't know why it works :)

In fact, let's make it more wizard!

1
2
3
4
5
6
7
8
int char_to_int (char input)
{
    if (input >= 060  &&  input  <= 57)
    {
      return input - 0x30;
    }
    throw std::exception();
}
Last edited on
Haha, very true.
Cheers ;)
Topic archived. No new replies allowed.