itoa
代码:
#include<iostream> using namespace std; void int2str(int n,char* str) { char buf[10] = " "; int len = 0; int temp = n<0?-n:n; int i = 0; if(str == NULL) { return ; } while(temp) { buf[i++] = (temp)+'0'; temp = temp/10; } len = n<0?++i:i; str[i] = 0; while(1) { i--; if(buf[len-i-1] == 0) break; str[i] = buf[len-i-1]; } if(i == 0) str[i] = '-'; } int main() { int n = 123; char str[10]; int2str(123,str); cout<<str<<endl; return 0; }
atoi
代码:
1 #include <iostream> 2 using namespace std; 3 4 int str2int(const char *str) 5 { 6 int temp = 0; 7 const char *ptr = str; //ptr保存str字符串开头 8 9 if (*str == '-' || *str == '+') //如果第一个字符是正负号, 10 { //则移到下一个字符 11 str++; 12 } 13 while(*str != 0) 14 { 15 if ((*str < '0') || (*str > '9')) //如果当前字符不是数字 16 { //则退出循环 17 break; 18 } 19 temp = temp * 10 + (*str - '0'); //如果当前字符是数字则计算数值 20 str++; //移到下一个字符 21 } 22 if (*ptr == '-') //如果字符串是以“-”开头,则转换成其相反数 23 { 24 temp = -temp; 25 } 26 27 return temp; 28 } 29 30 int main() 31 { 32 int n = 0; 33 char p[10] = ""; 34 35 cin.getline(p, 20); //从终端获取一个字符串 36 n = str2int(p); //把字符串转换成整型数 37 38 cout << n << endl; 39 40 return 0; 41 }