Darkstorm51 Darkstorm51 - 1 month ago 5x
C++ Question

C++ Base conversion unexpected output to screen during recursive function

I am writing a program that uses a recursive solution to convert a number to an indicated base. My issue is that the output to the screen only posts a single number (I'm guessing this is the last number). How can I properly return the remainders in order to the screen?

When viewing the call stack everything looks correct to me. I figure that I am missing something very simple or obvious.

Here is the section of my program that calls the BaseConverter funtion.

while (!File.eof())
File >> Decimal;
File >> Base;
// Check if values are valid
// function call BaseConverter (Decimal, Base);
cout << BaseConverter(Decimal, Base) << endl;


Recursive function to convert a decimal number to an indicated base.

int BaseConverter(int Decimal, int Base)
// Anchor Point
if (Decimal < Base)
return Decimal;
// Recursively divides the decimal by the base. Returns the remainder of the Decimal by the base while unwinding.
return BaseConverter(Decimal / Base, Base) % Base;


Because you are only returning single integer from function.

A correct implementation:

string ConvertBase(int num, int b) {

  if( b < 2 ||  b > 9 ) throw("Not supported");

  stringstream ss;

  if(num < b) {
      ss << num;
      return ss.str();

  ss << (num % b);

  return ConvertBase(num/b, b) + ss.str();


Note that for base higher than 9, you will need to have characters to represent those numbers.