在 C 中将 char 数组转换为 int 数 [英] Convert char array to a int number in C
问题描述
我想转换一个字符数组[],例如:
I want to convert a char array[] like:
char myarray[4] = {'-','1','2','3'}; //where the - means it is negative
所以应该是整数:-1234在C 中使用标准 库.我找不到任何优雅的方法来做到这一点.
So it should be the integer: -1234 using 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
库中 :)
It's very standard, it's in the stdio.h
library :)
在我看来,它比 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.
编辑我刚刚在解释和比较的网站上发现了这个美妙的问题3 种不同的方法 - atoi
、sscanf
和 strtol
.此外,还有对 sscanf
(实际上是整个 *scanf
函数系列)的更详细的了解.
EDIT
I 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
函数已被弃用,不应在较新的代码.
EDIT2
Looks 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 中将 char 数组转换为 int 数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!