Search code examples
c++numbersstring-parsing

How to interpret numbers correctly (hex, oct, dec)


I'm trying to write a program that takes input of - hexadecimals, octals, and decimals -, stores them in integer variables, and outputs them along with their conversion to decimal form. For example:

User inputs: 0x43, 0123, 65

Program outputs:

0x43 hexadecimal converts to 67 decimal
0123 octal converts to 83 decimal
65 decimal converts to 65 decimal

So obviously I need a way to interpret the numbers, but I'm not sure how to go about doing it. I've tried various methods such as reading them into a function and converting them into a string, and vice versa (see here for code examples), but interpreting the numbers always requires conversion to some format that trashes the original input.

The only thing I can think of is overloading a >> operator that reads a character at a time and if it sees 0x or 0 at the beginning of the input then it stores the whole input into a string before it is read into an int. Then the program would somehow have to determine the right manipulator during output.

Not sure if there is a simpler way to do this, any help is appreciated.

Edit: This has been solved, but I decided to post the code in if anyone is interested.

#include "std_lib_facilities.h"

void number_sys(string num, string& s)
{
  if(num[0] == '0' && (num[1] != 'x' && num[1] != 'X')) s = "octal";
  else if(num[0] == '0' && (num[1] == 'x' || num[1] == 'X')) s = "hexadecimal";
  else s = "decimal";
}

int main()
{
    cout << "Input numbers in hex, dec, or oct. Use 0xx to cancel.\n";
    string a;

    while(cin >> a){
    if(a == "0xx")break;
    string atype;
    number_sys(a, atype);

    int anum = strtol(a.c_str(), NULL, 0);

    cout << a << setw(20-a.length()) << atype << setw(20) << "converts to" << setw(10)
         << anum << setw(10) << "decimal\n";
                 }

    keep_window_open();
}

Solution

  • Take a look at the strtol function.

    char * args[3] = {"0x43", "0123", "65"};
    for (int i = 0; i < 3; ++i) {
      long int value = strtol(args[i], NULL, 0);
      printf("%s converts to %d decimal\n", args[i], value);
    }
    

    Outputs:

    0x43 converts to 67 decimal
    0123 converts to 83 decimal
    65 converts to 65 decimal