与书上的实现相比,自己的实现增加了自动判断字符串大小的部分 从而动态分配数组
#include <stdio.h>
#include <string>
#include<stdlib.h>
using namespace std;
void reverse(char s[]);
/*itoa function,change integer into string,savd in s[];*/
char* itoa(int n);
int main()
{
//test and I always forget add ";" in the end,becareful;
char*s=itoa(int(-189865554));
while(*s!='\0')
{
printf("%c",*s);
s++;
}
return 0;
}
void reverse(char s[])
{
//remember the strlen() function
int j=0;
int tmp;
//the fist time I code like this:for(int i=strlen(s)-1;i!=j;)
for(int i=strlen(s)-1;i>j;)
{
tmp=s[j];
s[j++]=s[i];
s[i--]=tmp;
}
}
char* itoa(int n)
{
/* first judge the space need in s for n*/
bool negetive=false;
int size=0;
int ncopy;
if(n<0)
{
negetive=true;
n*=-1;
size++;//for '-'
}
ncopy=n;
do {
ncopy=ncopy/10;
size++;
} while(ncopy>0);
//apply for space;
char *s=(char*)malloc(sizeof(char)*(size+1));//the "size" should add 1 for '\o'
int counter=0;
do {
s[counter]=n%10+'0';//do remember to add '0';
n=n/10;
//printf("\ns[counter])
counter++;
} while(n>0);
if (negetive)
{
s[counter++]='-';
}
s[counter]='\0';
reverse(s);
return s;
}