我试图找出是否有一种在C中转换字符串为整数的替代方法。
在我的代码中,我经常使用以下模式。
char s[] = "45";
int num = atoi(s);
那么,有没有更好的办法呢?
我试图找出是否有一种在C中转换字符串为整数的替代方法。
在我的代码中,我经常使用以下模式。
char s[] = "45";
int num = atoi(s);
那么,有没有更好的办法呢?
当前回答
在我看来,步行更好。我也喜欢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
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;
}
在我看来,步行更好。我也喜欢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) 除了错误的处理可能有所不同。如果不能为 表示,行为是未定义的。
//I think this way we could go :
int my_atoi(const char* snum)
{
int nInt(0);
int index(0);
while(snum[index])
{
if(!nInt)
nInt= ( (int) snum[index]) - 48;
else
{
nInt = (nInt *= 10) + ((int) snum[index] - 48);
}
index++;
}
return(nInt);
}
int main()
{
printf("Returned number is: %d\n", my_atoi("676987"));
return 0;
}
在c++中,你可以使用这样一个函数:
template <typename T>
T to(const std::string & s)
{
std::istringstream stm(s);
T result;
stm >> result;
if(stm.tellg() != s.size())
throw error;
return result;
}
这可以帮助您将任何字符串转换为任何类型,如float, int, double…