Re: C++ way to convert ASCII digits to Integer?
andreas.koestler@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'
To make the function usable also on non-ASCII implementations, and to
remove the need for a comment, you should write that last line as:
return asciidigit - '0';
}
Or you can use atoi or similar.
Better use strtol rather than atoi. It provides much better behaviour in
error situations.
Or you use the std::stringstream:
std::stringstream sstr("3");
int value;
sstr >> value;
Or you use boost::lexical_cast<> (which uses stringstreams internally,
but with proper error handling).
Hope that helps
Andreas
Bart v Ingen Schenau
--
a.c.l.l.c-c++ FAQ: http://www.comeaucomputing.com/learn/faq
c.l.c FAQ: http://c-faq.com/
c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/