问题描述
我想转换一个char []数组,如:
I want to convert a char array[] like:
char myarray[4] = {'-','1','2','3'}; //where the - means it is negative
因此,它应该是整数:-1234
使用标准在çlibaries 。我找不到任何优雅的方式来做到这一点。
So it should be the integer: -1234using standard libaries in C. I could not find any elegant way to do that.
我可以把'\\ 0'是肯定的。
I can append the '\0' for sure.
推荐答案
我个人不喜欢的atoi
功能。我建议的sscanf
:
I personally don't like atoi
function. I would suggest sscanf
:
char myarray[5] = {'-', '1', '2', '3', '\0'};
int i;
sscanf(myarray, "%d", &i);
这是非常标准的,它在 stdio.h中
库:)
在我看来,它可以让你比更自由的atoi
,你的电话号码串的任意格式,而且很可能还允许非数字字符结尾
And in my opinion, it allows you much more freedom than atoi
, arbitrary formatting of your number-string, and probably also allows for non-number characters at the end.
修改
我刚刚发现这个奇妙的question这里的介绍并比较3种不同的方式来做到这一点的网站 - 的atoi
,的sscanf
和 strtol将
。此外,还有一个很好的更详细的洞察的sscanf
(实际上,全家 * scanf函数
函数)。
EDITI just found this wonderful question here on the site that explains and compares 3 different ways to do it - atoi
, sscanf
and strtol
. Also, there is a nice more-detailed insight into sscanf
(actually, the whole family of *scanf
functions).
EDIT2
看起来它不只是我个人不喜欢的的atoi
功能。这里有一个一个答案解释说,的atoi
功能是德precated,不应该在新的code可以使用
EDIT2Looks like it's not just me personally disliking the atoi
function. Here's a link to an answer explaining that the atoi
function is deprecated and should not be used in newer code.
这篇关于转换字符数组在C INT编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!