1. Convert the string to an integer
There is no difficulty, that is, there are many situations to consider.
#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; // if it is a negative number, a negative number should be added, and left and right should go backward. If (Number <0) {Value =-Number; * str = '-'; left ++, right ++;} else Value = (unsigned) Number; // convert the number into a string (inverted) while (Value) {* right = (Value % 10) + 0x30; Value = Value/10; right ++ ;} * right -- = '\ 0'; // put the inverted string in front while (right> left) {ch = * left; * left ++ = * right; * right -- = ch;} return str ;}