In: Computer Science
Make a simple C++ program not complex
Following points are to be considered while making the program:
Step 1 : Save the following code in Conversion.cpp
#include <iostream>
#include <string>
using namespace std;
int main() {
int fromBase;
int toBase;
int input;
string binary;
while (true) {
// Display menu
cout << "Select Input Number Base" << endl;
cout << "1 for Binary" << endl;
cout << "2 for Octal" << endl;
cout << "3 for Decimal" << endl;
cout << "4 for Hexadecimal" << endl;
cout << "5 for Exit" << endl;
cin >> fromBase;
if (5 == fromBase) {
return 0;
}
cout << "Enter the number : ";
// For binary read string and use stoi() to convert to
integer.
// For others, use keyword like oct, dec hex etc
switch (fromBase) {
case 1 : cin >> binary; // string binary = "100100101"
input = stoi(binary, 0, 2);
break;
case 2 : cin >> oct >> input;
break;
case 3 : cin >> input;
break;
case 4 : cin >> hex >> input;
break;
default : cout << "Invalid choice";
break;
}
cout << "Select Output Number Base" << endl;
cout << "1 for conversion to Binary" << endl;
cout << "2 for conversion to Octal" << endl;
cout << "3 for conversion to Decimal" << endl;
cout << "4 for conversion to Hexadecimal" <<
endl;
cout << "5 for Exit" << endl;
cin >> toBase;
if (5 == toBase) {
return 0;
}
cout << "Output : ";
// For binary use for loop to extract every digit.
// For others, use keyword like oct, dec hex etc
switch (toBase) {
case 1: for (int i = 7; i >= 0; i--) {
cout << ((input >> i) & 1);
}
cout << endl;
break;
case 2: cout << oct << input << endl;
break;
case 3: cout << dec << input << endl;
break;
case 4: cout << hex << input << endl;
break;
default: cout << "Invalid choice";
break;
}
}
return 0;
}
Step 2 : Compile the program using g++ or visual studio and run.
Following is my sample output