字符串转换整数
输入一个由数字组成的字符串,把它转换成整数并输出
例如:输入字符串"123",输出整数123。
//字符串转换整数
#include<stdio.h>
#include<Windows.h>
//尽量不要溢出int类型的长度(2147483647)
char s[] = "-3574123123873";
void StrToInt(char* s, int LengthS);
int StrToIntFinal(const char* s);
void main()
{
int ArryLengthS = (sizeof(s)/sizeof(s[0])) - 1;
//StrToInt(s,ArryLengthS);
StrToIntFinal(s);
}
//简易算法
void StrToInt(char* s, int LengthS)
{
int n = 0;
for (int i = 0; i < LengthS; i++)
{
int c = s[i] - '0';
n = n * 10 + c;
printf("%d\n", n);
}
printf("%d\n", n);
}
//完善后的算法
int StrToIntFinal(const char* s)
{
static const int MAX_INT = (int)((unsigned)~0 >> 1);//MAX_INT=2147483647
static const int MIN_INT = -(int)((unsigned)~0 >> 1) - 1;//MIN_INT =-2147483648
unsigned int n = 0;//存放最终转换后的结果
/*printf("MAX_INT:%d\n", MAX_INT);
printf("MIN_INT:%d\n", MIN_INT);*/
//判断输入是否为空
if (s == 0)
{
return 0;
}
//处理空格
while (isspace(*s))
{
++s;
}
//处理正负
int sign = 1;
if (*s == '+' || *s == '-')
{
if (*s == '-')
sign = -1;
++s;
}
//确定数组中均为数字才执行循环
while (isdigit(*s))//判断数组中是否都是数字
{
//处理溢出
int c = *s - '0';
if (sign > 0 && (n > MAX_INT / 10 || (n == MAX_INT / 10 && c > MAX_INT % 10)))
{
n = MAX_INT;
printf("溢出上限\n");
break;
}
else if (sign < 0 && (n > (unsigned)MIN_INT / 10 || (n == (unsigned)MIN_INT / 10 && c > (unsigned)MIN_INT % 10)))
{
n = MIN_INT;
printf("溢出下限\n");
break;
}
//把之前得到的数字乘10,再加上当前字符表示的数字
n = n * 10 + c;
++s;
}
printf("%d\n",n);
return sign > 0 ? n : n*-1;
}