title: Decimal to Hex converter using Recursion (C++)
body: <p>Trying to write a program that converts a Decimal number to a Hexadecimal number <strong>that implements recursion.</strong></p>
  
  <p><strong>Can't use stuff like</strong></p>
  
  <pre><code>cout &lt;&lt; hex &lt;&lt; x &lt;&lt; endl; 
  </code></pre>
  
  <p><strong>Need to know how to write the function manually.</strong></p>
  
  <p>I tried this but it didn't really work:</p>
  
  <p>The input is an integer input by the user, and ss doesn't contain anything before this function.</p>
  
  <pre><code>string convertHex(int num, ostringstream &amp;ss)
  {
  
      int x = num % 16;
  
      switch (x)
      {
          case 10: ss &lt;&lt; "A"; return ss.str(); break;
          case 11: ss &lt;&lt; "B"; return ss.str(); break;
          case 12: ss &lt;&lt; "C"; return ss.str(); break;
          case 13: ss &lt;&lt; "D"; return ss.str(); break;
          case 14: ss &lt;&lt; "E"; return ss.str(); break;
          case 15: ss &lt;&lt; "F"; return ss.str(); break;
          default: ss &lt;&lt;   x; return ss.str(); break;
      }
  
      return convertHex(num / 16, ss);
  
  }
  </code></pre>
  
  <p>Not sure if I fully understand how to convert from Decimal to Hex, but what's hanging me up more is getting it to work with recursion. Any ideas? </p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I added in the if statement that was suggested by awesomeyi, and took out the returns in the switch, and now it sort of works... but not really. Here's the new code: </p>
  
  <pre><code>string convertHex(int num, ostringstream &amp;ss)
  {
  
      int x = num % 16;
  
      if (num == 0)
      {
          ss &lt;&lt; 0;
          return ss.str();
      }
  
      switch (x)
      {
          case 10: ss &lt;&lt; "A";  break;
          case 11: ss &lt;&lt; "B";  break;
          case 12: ss &lt;&lt; "C";  break;
          case 13: ss &lt;&lt; "D";  break;
          case 14: ss &lt;&lt; "E";  break;
          case 15: ss &lt;&lt; "F";  break;
          default: ss &lt;&lt; x;    break;
      }
  
      return convertHex(num / 16, ss);
  
  }
  </code></pre>
  
  <p>It works, but the output is backwards, and it adds a zero to the end of it. If I convert 16 in decimal to hex, it gives me 010. If I give it a bigger number like 4598, it gives me 6F110. The correct hex value for 4598 is 11F6.</p>
  
  <p>This is for a school assignment. Should I actually try to amend this? Or should I just flip it around after the function?</p>