Recursion assignment: print integer with commas

Trying to learn recursion. Problem asks to use recursion on non-negative number to insert commas. Ex: 20131 as 20,131. My program adds in an extra comma at end. Any help in pushing me in the correct direction to fix this would be appreciated.

input: 546789301
output: 546,789,301, <--note extra comma

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include "stdafx.h"
#include <iostream>

using namespace std;

void commaInsert(unsigned v)
{
	if (v <= 0) 
	{
		return; //base case
	}
	
	commaInsert(v/1000);
	cout<<(v%1000)<<",";
	return;
}

int main()
{
	unsigned input = 45678;
	//int count = 0;
	commaInsert(input);
	cout<<endl;
	return 0;
}

How about putting it all in a string, returning that, and checking if theres a comma at the end?
You don't want a comma int he end. The end is when v/1000 == 0. So change line 14 to
1
2
cout<<v%1000;
if(v/1000 > 0) cout<<',';
Thanks hamsterman. I played around with it and somehow got it working. If there is any other poor beginner that is assigned this problem, here is a working code set for your review.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <iomanip>

using namespace std;

void commaInsert(unsigned v)
{
	//base case
	if (v <= 0)
	{
		return;
	}
	//main logic
	commaInsert(v/1000);
	if(v >1000)
	{
		cout<<",";
		cout<<setfill('0')<<setw(3)<<(v%1000);  //stores on stack waiting for return
	}
	else
		cout<<(v%1000);  //stores on stack waiting for return
	return;
}

int main()
{
	while (true)
	{
		unsigned input;
		cout<<"Enter an integer to process: ";
		cin >> input;
		if (input == 0)		//special case
			cout<<"0"<<endl;
		else if (input == 1000)	//special case
			cout<<"1,000"<<endl;
		else
		{
			commaInsert(input);
			cout<<endl;
		}
	}
	return 0;
}

Topic archived. No new replies allowed.