Hatena::Groupcprogramming

C Study Diary

2008-12-22

c4ex11_itoa_recursive.cpp

17:30

Adapt the ideas of printd to write a recursive version of itoa ; that is, convert an integer into a string by calling a recursive routine.

Question: it may not be very smart to use an external variable as the string index, but I cannot think of a better way in the recursive routine. Suggestion welcomed!

#include <stdio.h>
#include <stdlib.h>
#include <string.h> 
#include <limits.h> 

#define MAX 20
 
int i;  /* string index */

/* put char to string */ 
void sputchar(char c, char* s){
	
	s[i++]=c;
	s[i]='\0';
}
 
void itoa(long n, char* s){
	
	i=0;
	if(n<0) {
		sputchar('-',s);
		n=-n;
	}	
	if(n/10==0) {
		sputchar(n%10+'0',s);
	}else{
		itoa(n/10,s);
		sputchar(n%10+'0',s);
	}
	
}

int main(void){

	long a = -1122333;
	char *buff;
	
	itoa(a, buff);
	printf("itoa(%d)=%s\n",a,buff);
	a =890556;
	itoa(a, buff);
	printf("itoa(%d)=%s\n",a,buff);

	return 0;
}

Run:

$ ./c4ex11_itoa_recursive.exe
itoa(-1122333)=1122333
itoa(890556)=890556