May 10, 2017 at 5:42pm UTC
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).
May 10, 2017 at 6:12pm UTC
Last edited on May 10, 2017 at 6:16pm UTC
May 10, 2017 at 7:03pm UTC
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.
May 10, 2017 at 7:04pm UTC
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 May 10, 2017 at 7:08pm UTC
May 10, 2017 at 7:06pm UTC
Haha, very true.
Cheers ;)