您的位置:首页 > 其它

提取字符串中的数字,如''123" ,结果123,考虑各种情况

2014-03-26 16:34 218 查看
#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,-23243243243433printf("the num is %d\n",StrToInt(str));return 1;}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐