tags:

views:

63

answers:

2

Hi,

So as we all probably know, the atoi converts a char to a number. But, what do you do if you only want one of the array elements instead of the whole array?

Please look at the following:

for (h = 0; h < 5; h++)
{
    num[h] = atoi(temp[h]);
}

Assume that num is an array of type int and that temp is and array of type char. This gives me one of those annoying conversion problems:

Invalid conversion from 'char' to 'const char *'

Any suggestions on how to convert a single element of a char array to an int using atoi?

+7  A: 

If you only want to convert a single character you don't need to use atoi():

if (temp[h] >= '0' && temp[h] <= '9')
{
    num[h] = temp[h] - '0';
}
else
{
    // handle error:  character was not a digit
}

In C, the value of each digit is one greater than the value of the previous digit, so this is guaranteed to work.

The reason that atoi() does not work is because it takes a const char* as its argument, not a char. That pointer has to point to a null terminated string.

James McNellis
Ok... I thought you needed to convert using atoi(). Thanks.
thyrgle
@kriss: Thanks for the semicolon! Oops!
James McNellis
C does not define the character encoding, so this is not "guaranteed to work". You are assuming the character encoding is ASCII (or has the desired property), which is perhaps a reasonable assumption but it's important to know it's a assumption, not a guarantee.
@.yahoo.co: "In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous" (C99 §5.2.1/3).
James McNellis
@James McNelis Yow, did not know that. I am still thinking in C89. Thanks.
@.yahoo.co: That same sentence is in C89/90 §2.2.1. You're welcome.
James McNellis
@yahoo: and this trick works for ages on non ASCII charset like EBCDIC, not just ASCII.
kriss
The first if can be written more efficiently as `if ((unsigned)temp[h]-'0'<10)`.
R..
+3  A: 

Besides just using its integral value as shown by James, you could put it in a seperate buffer:

char buf[2] = { temp[h], '\0' };
num[h] = atoi(buf);
Georg Fritzsche