字符串和int转换函数实现
//不使用库函数将整数转换为字符串,输入 int 输出 char*
#include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ char* IntoString(int num); //转换函数 int main(int argc, char** argv) { char *p1 = IntoString(-123); char *p2 = IntoString(13345666); while(*p1!='\0') std::cout<<*(p1++); std::cout<<std::endl; while(*p2!='\0') std::cout<<*(p2++); std::cout<<std::endl; delete p1; delete p2; return 0; } char* IntoString(int num) { int length = 0; if(num == 0) { return NULL ; } int temp_num = (num > 0 ? num: -num); while(temp_num!=0) //求正数的长度 { ++length; temp_num/=10; } int Yu = 0; if(num>0) //处理正整数 { char *pstr = new char[length + 1]; pstr[length] = '\0'; int Op_num = num; int n = length-1; while(Op_num !=0) { Yu = Op_num % 10; pstr[n--] = Yu+'0'; Op_num /= 10; } return pstr; } else { char *pstr = new char[length + 2]; //处理负整数 pstr[length+1] = '\0'; int Op_num = -num; int n = length; while(Op_num !=0) { Yu = Op_num % 10; pstr[n--] = Yu+'0'; Op_num /= 10; } pstr[0] = '-'; return pstr; } }
//不使用库函数将字符串转换为整数 //karllen #include <iostream> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int StringToInt(const char *pstr); int main(int argc, char** argv) { char one[] = "1234"; char two[] = "-14343"; std::cout<<StringToInt(one)<<std::endl; std::cout<<StringToInt(two)<<std::endl; return 0; } int StringToInt(const char *pstr) { int tempint = 0; const char *pt = pstr; if(*pt == '+' || *pt =='-') { ++pt; } while(*pt!='\0') { tempint = tempint*10 + (*pt - '0'); ++pt; } if(*pstr == '-') { tempint = -tempint; } return tempint; }
书到用时方恨少,是非经过不知难。
博观而约取,厚积而薄发。@karllen 每天进步一点点。