Re: C++ way to convert ASCII digits to Integer?
On May 27, 3:30 am, "andreas.koest...@googlemail.com"
<andreas.koest...@googlemail.com> wrote:
On May 27, 9:18 am, "Peter Olcott" <NoS...@SeeScreen.com> wrote:
I remember that there is a clean C++ way to do this, but, I
forgot what it was.
I don't know what you mean by 'clean C++ way' but one way to
do it is: int ascii_digit_to_int ( const char asciidigit ) {
if ( asciidigit < '0' ||
asciidigit > '9' ) {
throw NotADigitException();
}
return (int) asciidigit - 48; // 48 => '0'
That's wrong. There's no guarantee that '0' is 48. I've worked
on machines where it is 240. (Of course, the term asciidigit is
very misleading on such machines, because you're really dealing
with an ebcdicdigit.)
You are guaranteed that the decimal digits are consecutive, so
digit - '0' works. Of course, as soon as you do that, someone
will ask for support for hexadecimal. The simplest solution is
just to create a table, correctly initialize it, and then:
return table[ digit ] < 0
? throw NotADigitException()
: table[ digit ] ;
}
Or you can use atoi or similar.
Or you use the std::stringstream:
std::stringstream sstr("3");
int value;
sstr >> value;
That's the normal way of converting a stream of digits into a
number in internal format.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34