itoa函数:将数字n转换为字符串并保存到s中 3.6例题实现

来源:互联网 发布:软件技术支持前景 编辑:程序博客网 时间:2024/05/21 09:47
#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() functionint 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;}

0 0