Letting the user make a choice

I have written a program that converts a decimal number into binary, hexadecimal, and octal. The program needs to ask the user what they want to convert to and then print the answer. I have tried using if else statements but they create errors.
Here is my code
 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475`` ``````#include "stdafx.h" #include #include using namespace std; void binary(int); int main(void) { int number,h,o; cout << "Enter a positive integer: "; cin >> number; if (number < 0) cout << "That is not a positive integer.\n"; else { cout << number << " converted to binary is: "; binary(number); cout << endl; long int remainder,quotient; int i=1,j,temp; char hexadecimalNumber[100]; quotient = number; while(quotient!=0){ temp = quotient % 16; if( temp < 10) temp =temp + 48; else temp = temp + 55; hexadecimalNumber[i++]= temp; quotient = quotient / 16; } cout< 0;j--) printf("%c",hexadecimalNumber[j]); cout< 0;y--) printf("%d",octalNumber[y]); cout<>choice; } void binary(int number) { int remainder; if(number <= 1) { cout << number; return; } remainder = number%2; binary(number >> 1); cout << remainder; }``````
Try putting each conversion into its own function, and instead of using a `void` function, make it return an `int`.

There are a number of different ways to give the user a choice. For example, you could use a string, or maybe an int.

eg.

 ``1234567891011121314151617181920212223242526272829303132`` ``````int choice; cout << "What would you like to convert to?" << endl; cout << "1-Binary" << endl << "2-Hex" << endl << "3-Octal" << endl; cin >> choice; switch (choice) { case 1: cout << binary(choice) << endl; break; case 2: cout << hex(choice) << endl; break; case 3: cout << octal(choice) << endl; break; } //or alternatively... if(choice == 1) cout << binary(n) << endl; else if(choice == 2) cout << hex(n) << endl; else if(choice == 3) cout << octal(n) << endl;``````

Using a string would allow the user to type what they want:

 ``123456789101112`` ``````string choice; cout << "What would you like to convert to?" << endl; cin >> choice; if(choice == "binary") cout << binary(n) << endl; else if(choice == "hex" || choice == "hexadecimal") cout << hex(n) << endl; else if(choice == "octal") cout << octal(n) << endl;``````

The string option could also be done in a switch statement, as with an int: Wrong!
Last edited on
Sadly, you can't switch on strings in C++, so you'll have to pass on that. The other ways should work, though.
yea i figured that I should make hex and octal functions, I went with this route because i couldn't get my original functions to work. I'll try what you said, thankyou
Aah yes, Moeljbcp, my mistake.
Topic archived. No new replies allowed.