Sep 6, 2012 at 6:22am UTC
I need to create a recursive function that converts a int to a string.
The base case would be: input is from 0 to 9 and return the value as a string.
How would you return it a string?
I am not allowed to use atoi, itoa, for or while. Or anything similar to itoa or atoi.
It would look something like?
if(n==0) return 0?
Sep 6, 2012 at 9:38pm UTC
This is what I have so-far:
I need help with the base cases? I cannot use for or while loops.
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
int main()
{
/*/int tests[] = {
0, 100, -5, 10, 5, 10302
};
const int B = 6;
for (int i=0; i<B; i++)
{
cout << "Converting the integer "<< tests[i] <<" to string: ";
cout << intToStr(tests[i]) << endl;
}*/
int num;
cout<<"Please input a number: " ;
cin>>num;
cout<<endl;
cout<<"Converting the integer " <<num<<" to a string: " ;
cout<<intToStr(num)<<endl;
//string str;
system("PUASE" );
return 0;
}
string intToStr(int n)
{
if (
}
Last edited on Sep 6, 2012 at 9:39pm UTC
Sep 6, 2012 at 9:49pm UTC
Do you mean std::string or a character array?
If you mean a character array then the function is simple
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
#include <iostream>
#include <limits>
char * intToStr( char *p, unsigned int number )
{
char digit = number % 10 + '0' ;
if ( number /= 10 ) p = intToStr( p, number );
*p++ = digit;
return ( p );
}
int main()
{
char s[std::numeric_limits<unsigned int >::digits10 + 2];
unsigned int number = 123456789;
char *p = intToStr( s, number );
*p = '\0' ;
std::cout << "s = " << s << std::endl;
}
Last edited on Sep 6, 2012 at 9:59pm UTC
Sep 7, 2012 at 3:37am UTC
Although my attempt isn't terribly readable, it's recursive and it handles both positive and negative integers correctly:
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
#include <iostream>
#include <string>
using namespace std;
string i_str(int num)
{
string s;
static bool recursive_call = false ; //is this a recursive call?
if (!recursive_call) {
if (!num) return "0" ; //deal with zero
else if (num < 0) { //account for negative numbers
num *= -1;
s += '-' ;
}
recursive_call = true ; //get ready for recursive calls
}
else if (!num) { //conversion is complete, reset function for future calls
recursive_call = false ;
return "" ;
}
char app = num % 10 + '0' ; //convert to a character
return s + i_str(num / 10) + app; //append the characters in the correct order
}
int main()
{
cout<< i_str(-456) << '\n' << i_str(-345) << '\n' << i_str(647)
<< '\n' << i_str(235) << '\n' << i_str(4532175) << '\n' << i_str(-99567);
cin.get();
}
Last edited on Sep 7, 2012 at 3:37am UTC