C语言 如何在C中将字符串转换为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7021725/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a string to integer in C?
提问by user618677
I am trying to find out if there is an alternative way of converting string to integer in C.
我试图找出在 C 中是否有将字符串转换为整数的替代方法。
I regularly pattern the following in my code.
我经常在我的代码中模式化以下内容。
char s[] = "45";
int num = atoi(s);
So, is there a better way or another way?
那么,有没有更好的方法或其他方法?
采纳答案by cnicutar
There is strtolwhich is better IMO. Also I have taken a liking in strtonum, so use it if you have it (but remember it's not portable):
有strtol哪个更好的 IMO。我也很喜欢strtonum,所以如果你有它,请使用它(但请记住它不是便携式的):
long long
strtonum(const char *nptr, long long minval, long long maxval,
const char **errstr);
EDIT
编辑
You might also be interested in strtoumaxand strtoimaxwhich are standard functions in C99. For example you could say:
您可能还对C99 中的标准函数strtoumax和strtoimax哪些函数感兴趣。例如你可以说:
uintmax_t num = strtoumax(s, NULL, 10);
if (num == UINTMAX_MAX && errno == ERANGE)
/* Could not convert. */
Anyway, stay away from atoi:
无论如何,远离atoi:
The call atoi(str) shall be equivalent to:
(int) strtol(str, (char **)NULL, 10)except that the handling of errors may differ. If the value cannot be represented, the behavior is undefined.
调用 atoi(str) 应等同于:
(int) strtol(str, (char **)NULL, 10)除了对错误的处理可能有所不同。如果无法表示该值,则行为是 undefined。
回答by AnT
Don't use functions from ato...group. These are broken and virtually useless. A moderately better solution would be to use sscanf, although it is not perfect either.
不要使用ato...组中的函数。这些都坏了,几乎没用。一个适度更好的解决方案是使用sscanf,尽管它也不完美。
To convert string to integer, functions from strto...group should be used. In your specific case it would be strtolfunction.
要将字符串转换为整数,strto...应使用 group 中的函数。在您的特定情况下,它将是strtol功能。
回答by jDourlens
You can code a little atoi() for fun:
你可以编写一些 atoi() 来获得乐趣:
int my_getnbr(char *str)
{
int result;
int puiss;
result = 0;
puiss = 1;
while (('-' == (*str)) || ((*str) == '+'))
{
if (*str == '-')
puiss = puiss * -1;
str++;
}
while ((*str >= '0') && (*str <= '9'))
{
result = (result * 10) + ((*str) - '0');
str++;
}
return (result * puiss);
}
You can also make it recursive wich can old in 3 lines =)
你也可以让它递归,它可以在 3 行中变老 =)
回答by Jacob
Just wanted to share a solution for unsigned long aswell.
只是想分享一个 unsigned long 的解决方案。
unsigned long ToUInt(char* str)
{
unsigned long mult = 1;
unsigned long re = 0;
int len = strlen(str);
for(int i = len -1 ; i >= 0 ; i--)
{
re = re + ((int)str[i] -48)*mult;
mult = mult*10;
}
return re;
}
回答by Biswajit Karmakar
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;
}
回答by Amith Chinthaka
This function will help you
此功能将帮助您
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 != '#include <stdio.h>
#include <string.h>
#include <math.h>
int my_atoi(const char* snum)
{
int idx, strIdx = 0, accum = 0, numIsNeg = 0;
const unsigned int NUMLEN = (int)strlen(snum);
/* Check if negative number and flag it. */
if(snum[0] == 0x2d)
numIsNeg = 1;
for(idx = NUMLEN - 1; idx >= 0; idx--)
{
/* Only process numbers from 0 through 9. */
if(snum[strIdx] >= 0x30 && snum[strIdx] <= 0x39)
accum += (snum[strIdx] - 0x30) * pow(10, idx);
strIdx++;
}
/* Check flag to see if originally passed -ve number and convert result if so. */
if(!numIsNeg)
return accum;
else
return accum * -1;
}
int main()
{
/* Tests... */
printf("Returned number is: %d\n", my_atoi("34574"));
printf("Returned number is: %d\n", my_atoi("-23"));
return 0;
}
')
{
n++;
temp++;
}
return strtoint_n(str, n);
}
Ref: http://amscata.blogspot.com/2013/09/strnumstr-version-2.html
参考:http: //amscata.blogspot.com/2013/09/strnumstr-version-2.html
回答by ButchDean
You can always roll your own!
你可以随时推出自己的!
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;
}
This will do what you want without clutter.
这将做你想做的事情而不会造成混乱。
回答by Khaled Mohammad
Ok, I had the same problem.I came up with this solution.It worked for me the best.I did try atoi() but didn't work well for me.So here is my solution:
好吧,我遇到了同样的问题。我想出了这个解决方案。它对我来说效果最好。我确实尝试过 atoi() 但对我来说效果不佳。所以这是我的解决方案:
//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;
}
回答by Aditya Kumar
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;
}
回答by neodelphi
In C++, you can use a such function:
在 C++ 中,您可以使用这样的函数:
##代码##This can help you to convert any string to any type such as float, int, double...
这可以帮助您将任何字符串转换为任何类型,例如 float、int、double...

