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

限于喜欢 提交于 2019-11-29 07:05:45
James McNellis

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.

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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!