/*

将数字字符串,转换成整数输出

例:“1234”输出 1234

*/


#include<stdio.h>


int str_validity = 0;

int charnum_to_int(char *str)

{

int num = 0, i = 0;

if (str == NULL)

{

str_validity = 1;

return 0;

}

if (*str == '-' || *str == '+')

{

i = '*str';

while (*(++str))

{

int num1;

if (*str >= 48 && *str <= 57)

{

if (*str == '0'&&num == 0)

continue;

else

num = num * 10 + (*str - 48);

num1 = num;

if ((num1&(1 << 31)) < 0)

str_validity = 1;

}

else

{

str_validity = 1;

break;

}


}

if (i == '-')

return num*-1;

else

return num;

}

while (*str)

{

int num1;

if (*str >= 48 && *str <= 57)

{

if (*str == '0'&&num == 0)

continue;

else

num = num * 10 + (*str - 48);

num1 = num;

if ((num1&(1 << 31) )< 0)

{

str_validity = 1;

break;

}

}

else

{

str_validity = 1;

break;

}

str++;

}

return num;

}


int main()

{

char *str = "-02147483647";//2 ^32

int num = 0;

num=charnum_to_int(str);

if (str_validity == 0)

printf("%d\n", num);

else

printf("该字符串不合法\n");

return 0;

}