Integer to string - How?

Write your question here.
Hi, I need to present a number as string, but only with recursion.
I made it, but the the problem is that it's reversed.
What should i do?

1
2
3
4
5
6
7
8
9
10
11
  void intToStr(unsigned int num, char s[]) {

	int l= strlen(s);
	char ch = char(num%10 + 48);
	if (num<10) {
		s[l] = ch;
	} else {
		s[l] = ch;
		intToStr(num/10, s);
	}
}
You could shift the contents of the array to the right by one every time.
Then you would put the next digit at the front in position 0.


Edit: see abhishekm71's solution below.
Last edited on
But how?
Initially the length is zero. Hence the first character (unit's place) gets added to the 1st place of s.

Hence the string gets built in reverse.

The solution is to first go deep into recursion, and then after coming back, add the character.

1
2
3
4
5
6
7
8
9
10
11
void intToStr(unsigned int num, char s[]) {

	int l= strlen(s);
	char ch = char(num%10 + 48);
	if (num<10) {
		s[l] = ch;
	} else {
		intToStr(num/10, s);
		s[l] = ch;
	}
}

-char s[] is wrong here because you can't increase the length of an array (except if you know the maximum size of the string which will be a correct but not very good solution to the problem).
You can use a double pointer like char **s but it will be too complicated and it'll take longer time because you'll have to do dynamic allocation on each recursion!
The best method is to use the string object in <string> header file.

- The second error which is the main problem is in the else statement: you should invert lines 8 and 9 to obtain it in correct order like abhishekm71 said before
Topic archived. No new replies allowed.