On Mon, 27 Oct 2003 13:54:06 +0100
"Rick" <as******@hotmail.com> wrote:
Another newbie question. I'm trying to convert a char to an integer.
My input is a string which holds a number on place 4. However, if I
try
int number = atoi( input[3] );
I'll get an error because of the type conversion I guess. Atoi wants a
string while I put a single char into it. So I tried it another way:
char s[2];
int number;
s[0] = input[3];
s[1] = 0;
number = atoi( s );
That worked but aren't their better ways?
That depends on what you mean by "convert a char to an integer". If you
want to convert a single character in the range '0' to '9' then
int val='5'-'0'; /* val is guaranteed to be 5 */
So for your example
/* do some data validation */
number = input[3] - '0';
NOTE: The whilst the ordering of characters '0' to '9' is guaranteed by
the standard the rest of the character set has no such guarantee so, for
example, reporting which letter of the alphabet 'c' is requires
something a bit more than 1 + 'c' - 'a'
--
Mark Gordon
Paid to be a Geek & a Senior Software Developer
Although my email address says spamtrap, it is real and I read it.