我试图找出是否有一种在C中转换字符串为整数的替代方法。
在我的代码中,我经常使用以下模式。
char s[] = "45";
int num = atoi(s);
那么,有没有更好的办法呢?
我试图找出是否有一种在C中转换字符串为整数的替代方法。
在我的代码中,我经常使用以下模式。
char s[] = "45";
int num = atoi(s);
那么,有没有更好的办法呢?
当前回答
不要使用来自ato…组。这些都坏了,几乎毫无用处。一个稍好的解决方案是使用sscanf,尽管它也不是完美的。
将字符串转换为整数,函数from strto…应该使用Group。在你的具体情况下,它将是strotol函数。
其他回答
在我看来,步行更好。我也喜欢strtonum,所以如果你有它就使用它(但记住它不方便携带):
long long
strtonum(const char *nptr, long long minval, long long maxval,
const char **errstr);
你可能还会对strtoumax和strtoimax感兴趣,它们是C99中的标准函数。例如,你可以说:
uintmax_t num = strtoumax(s, NULL, 10);
if (num == UINTMAX_MAX && errno == ERANGE)
/* Could not convert. */
不管怎样,远离atoi:
调用atoi(str)应该等价于: (int) strtol(str, (char **)NULL, 10) 除了错误的处理可能有所不同。如果不能为 表示,行为是未定义的。
这个函数会帮助你
int strtoint_n(char* str, int n)
{
int sign = 1;
int place = 1;
int ret = 0;
int i;
for (i = n-1; i >= 0; i--, place *= 10)
{
int c = str[i];
switch (c)
{
case '-':
if (i == 0) sign = -1;
else return -1;
break;
default:
if (c >= '0' && c <= '9') ret += (c - '0') * place;
else return -1;
}
}
return sign * ret;
}
int strtoint(char* str)
{
char* temp = str;
int n = 0;
while (*temp != '\0')
{
n++;
temp++;
}
return strtoint_n(str, n);
}
裁判:http://amscata.blogspot.com/2013/09/strnumstr - - 2.版本的html
好吧,我也有同样的问题。我想出了这个解决方案。这对我来说是最有效的。我试过用atoi(),但效果不太好。下面是我的解决方案:
void splitInput(int arr[], int sizeArr, char num[])
{
for(int i = 0; i < sizeArr; i++)
// We are subtracting 48 because the numbers in ASCII starts at 48.
arr[i] = (int)num[i] - 48;
}
是的,你可以直接存储整数:
int num = 45;
如果你必须解析一个字符串,atoi或strol将赢得“最短代码量”的比赛。
int atoi(const char* str){
int num = 0;
int i = 0;
bool isNegetive = false;
if(str[i] == '-'){
isNegetive = true;
i++;
}
while (str[i] && (str[i] >= '0' && str[i] <= '9')){
num = num * 10 + (str[i] - '0');
i++;
}
if(isNegetive) num = -1 * num;
return num;
}