#include<stdio.h>
#include<stdlib.h>
//从这个例子就可以看出,在编写程序时尤其在面试时,先写好测试用例的重要性
//考虑负数,数据溢出,非数字字符,以及变量的命名是否规范,特别对于字符串判断非空最基本的一定要有,否则程序放在软件中会出现段错误,这时候
//带来的后果非常大
int StrToInt(const char *s)
{
int result=0;
if(!s)
printf("parameter is null\n");
if(*s!='-')
{
while(*s !='\0')
{
if( (*s-'0')>9 || (*s-'0')<0 )
{
printf("the input contains other character\n");
exit(-1);
}
result=*s-'0'+10*result;
s++;
if(result <0)
{
printf("the input overfolw\n");
exit(-1);
}
}
}
else
{
s++;
while(*s !='\0')
{
if( (*s-'0')>9 || (*s-'0')<0 )
{
printf("the input contains other character\n");
exit(-1);
}
result=*s-'0'+10*result;
s++;
if(result<0)
{
printf("the input is overflow\n");
exit(-1);
}
}
result=-result;
}
return result;
}
int main()
{
char str[50];
scanf("%s",str); //测试用例:true: 0, 12,-237, false: 23sd,23472847834345,-23243243243433
printf("the num is %d\n",StrToInt(str));
return 1;
}