I need help with a program that I am working on. Basically the program right now takes a decimal number and converts it into whichever base I choose. What I need it to do is accept other inputs initially (binary, hexa, octal) and convert between whichever I choose. Can anyone point me in the right direction? Here is what I have so far:

#include <iostream>
#include <stdexcept>
#include <string>

using namespace std;

int main() try
    cout << "Enter a number and base: ";

    int num, base;

    if (cin >> num >> base) {
        if (base < 2 || base > 36)
            throw out_of_range("Invalid base for conversion");

        // Define an alphabet for the largest supported base
        const string digits("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");
        bool is_neg = num < 0;
        string result;

        for (; num; num /= base) {
            // Note: abs() is done on each digit instead of the whole num 
            // to preserve the full range of int
            result.insert(result.begin(), digits[abs(num % base)]);

        if (is_neg)
            result.insert(result.begin(), '-');

        cout << result << '\n';
    else {
        cerr << "Invalid input\n";
catch (const out_of_range& ex)
    cerr << ex.what() <<'\n';

Write it in two stages, perhaps.

You already have the code for converting a decimal number to some specified base.
Write the code to convert in the reverse direction - from some specified base to decimal.

Now conversion from base A to base B can be done in stages:

  • Convert number in base A to decimal.
  • Convert the decimal result to base B.
Be a part of the DaniWeb community

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