为避免与标准库中的atoi产生歧义,
我将自己编写的函数命名为strToInt,
以下是示例代码
#include <stdio.h>
int strToInt(const char *str);
int main()
{
int a = strToInt("-123.456");
int b = strToInt("+3.14");
int c = strToInt("123+123");
int d = strToInt("0001a2");
int e = strToInt("-+567");
printf("%d %d %d %d %d
", a, b, c, d, e);
return 0;
}
int strToInt(const char *str)
{
int signedFlag = 1;
int sum = 0;
if (*str == '+')
{
++str;
}
else if (*str == '-')
{
signedFlag = -1;
++str;
}
while (*str >= '0' && *str <= '9')
{
sum = sum * 10 + *str++ - '0';
}
return signedFlag * sum;
}