来源:自学PHP网 时间:2015-04-14 14:51 作者: 阅读:次
[导读] 1.将字符串转换成整数 没什么难点,就是考虑的情况比较多。#includeiostream #includecctype #includeexception #includeclimits #includecstdio using namespace std; long Str2Num(cons......
1.将字符串转换成整数 没什么难点,就是考虑的情况比较多。
#include<iostream> #include<cctype> #include<exception> #include<climits> #include<cstdio> using namespace std; long Str2Num(const char *str) { if(!str)throw new std::exception("NULL String"); bool isNegetive = false; int radix = 10; unsigned long ret = 0; if(*str == '-'){ isNegetive = true; ++str; }else if(*str == '+')++str; if(*str == '0'&&(str+1)&&*(str+1)!='x'&&*(str+1)!='0'){ radix = 8; ++str; } else if(*str == '0'&& tolower(*(str+1))=='x'){ radix = 16; ++str;++str; } for(;*str!='\0';++str){ int ch = *str; if((ch - '0') <radix){ ret = ret*radix + ch - '0'; } else if(radix == 16 && ('a'<=tolower(ch)&&tolower(ch)<='f')){ ret = ret*radix + tolower(ch) - 'a' + 10; } else throw new exception("Invalid num"); if(ret>LONG_MAX)throw new exception("overfolw"); } return isNegetive?(-ret):ret; } #include<iostream> #include<cctype> #include<exception> #include<climits> #include<cstdio> using namespace std; long Str2Num(const char *str) { if(!str)throw new std::exception("NULL String"); bool isNegetive = false; int radix = 10; unsigned long ret = 0; if(*str == '-'){ isNegetive = true; ++str; }else if(*str == '+')++str; if(*str == '0'&&(str+1)&&*(str+1)!='x'&&*(str+1)!='0'){ radix = 8; ++str; } else if(*str == '0'&& tolower(*(str+1))=='x'){ radix = 16; ++str;++str; } for(;*str!='\0';++str){ int ch = *str; if((ch - '0') <radix){ ret = ret*radix + ch - '0'; } else if(radix == 16 && ('a'<=tolower(ch)&&tolower(ch)<='f')){ ret = ret*radix + tolower(ch) - 'a' + 10; } else throw new exception("Invalid num"); if(ret>LONG_MAX)throw new exception("overfolw"); } return isNegetive?(-ret):ret; char * Num2Str(int Number) { char ch,*str,*right,*left; unsigned int Value; str = (char *)malloc(12*sizeof(char)); left = right = str; //如果是负数,则应加上负号,left、right向后走。 if(Number < 0) { Value = -Number; *str = '-'; left++,right++; } else Value = (unsigned)Number; //把数字转换成字符串(倒置的) while(Value) { *right = (Value%10)+0x30; Value = Value/10; right++; } *right-- = '\0'; //把倒置的字符串正放过来 while(right > left) { ch = *left; *left++ = *right; *right-- = ch; } return str; }
|
自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习
京ICP备14009008号-1@版权所有www.zixuephp.com
网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com