Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

c - How do you use atoi to assign individual elements of a char array?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...