The objective: take an integer (e.g. 1000000), and by using recursion, ultimately return this string: 1,000,000.

Can anyone figure out how this problem could be solved specifically by taking an integer and returning a string?


string addCommas(int n)
{
// ???

}


Thanks for any help or direction

Recommended Answers

All 4 Replies

Int to string is easy in C++ with a "stringstream", or if you prefer you can use an old C function.

int someInt = 256;
string out;
stringstream(someInt) >> out;

Int to string is easy in C++ with a "stringstream", or if you prefer you can use an old C function.

int someInt = 256;
string out;
stringstream(someInt) >> out;

And how does stringstream solve
1) recursion
2) comma-separated blocks?
It helps to read carefully... :icon_rolleyes:

Hey Kid, read the forum rules and add the information you forgot.

And how does stringstream solve
1) recursion
2) comma-separated blocks?
It helps to read carefully... :icon_rolleyes:

Hey Kid, read the forum rules and add the information you forgot.

It's a good start at least. For recursion you'll usually want to keep your data around, often times by passing it as argument to the function's parameters. I suppose (according to your needs) you could make a static string inside the function.

Oh and actually that doesn't convert an int to string! (oops)

template<typename T>
string ToString( T in )
{
	stringstream ss;
	ss << in;
	return ss.str();
}

As pseudorandom suggested, the first step would be to convert the integer to a string.
Alternatively, if you want to skip that step, you could just get a string from the user.

Now, let's take a look at the algorithm...

Suppose the user enters this -> "1234567890" . The result of add_commas("1234567890") should
be this -> "1,234,567,890" . One way to use recursion would be to make your function work as follows:

add_commas("1234567890") = 

add_commas("1234567") + "," + "890" = 

( add_commas("1234") + "," + "567" ) + "," + "890" = 

( ( add_commas("1") + "," + "234" ) + "," + "567" ) + "," + "890" = 

( ( "1" + "," + "234" ) + "," + "567" ) + "," + "890" = 

( "1,234" + "," + "567" ) + "," + "890" = 

"1,234,567" + "," + "890" = 

"1,234,567,890"

That is, if the string's length is 3 or less, add_commas should return the string intact. Otherwise, it should
break it into two parts, the right one consisting of the 3 rightmost digits and the left one being the rest
of the string. Then, the function should return add_commas(left_part) + "," + right_part Useful link -> http://cplusplus.com/reference/string/string/substr/

Encrypted hint -> Difdl!uif!uisfbet!J!tubsufe/

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.