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!=' ';++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; }
2.将整数转换成字符串(借用别人的,感觉还是有些情况没考虑到)
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-- = ' '; //把倒置的字符串正放过来 while(right > left) { ch = *left; *left++ = *right; *right-- = ch; } return str; }