Here is what appears to be a fairly easy problem:
Write a program that prompts the user to enter several integers in any combination of
octal
,decimal
, orhexadecimal
, using the0
and0x
base prefixes; interprets the numbers correctly; and converts them to decimal form. Then your program should output the values in properly spaced columns like this:0x4 hexadecimal converts to 4 decimal 0123 octal converts to 83 decimal 65 decimal converts to 65 decimal
Here is a first (working) draft:
const string info ("This program recognizes multiple base prefixed numbers dec:none, hex:0x, oct:0\nand converts them into decimals.\n");
const string prompt ("Please enter numbers with random base prefixes.\n>>");
const char octprefix ('0');
const char hexprefixLower ('x');
const char hexprefixUpper ('X');
const int inputLoop = 2;
int main(){
try{
cout << info;
string num;
vector<string> inputNumbers;
int numDecimals(0);
vector <int> inputDecimals;
for (int i=0; i < inputLoop; i++){
// get number with prefix
cout << prompt;
cin >> num;
inputNumbers.push_back(num);
// return number (# of characters) back to cin stream for reinterpretation
for (int i=0; i < num.length(); i++) cin.unget();
// unset default flags so that prefixes are considered
// and numbers with different bases converted directly to decimals
cin.unsetf(ios::dec | ios::oct | ios::hex);
cin >> numDecimals;
inputDecimals.push_back(numDecimals);
}
// discern base from prefix
// checks first two characters of every vector element to determine base prefix
for (int i=0; i < inputNumbers.size(); i++){
if (inputNumbers[i][0] != octprefix){
cout << inputNumbers[i] <<" decimal "<<" converts to "<< inputDecimals[i] <<" decimal\n";
}
if (inputNumbers[1][0] == octprefix && (inputNumbers[1][1] != hexprefixLower && inputNumbers[1][1] != hexprefixUpper)){
cout << inputNumbers[i] <<" octal "<<" converts to " << inputDecimals[i] <<" decimal\n";
}
if (inputNumbers[1][0] == octprefix && (inputNumbers[i][1] == hexprefixLower || inputNumbers[i][1] == hexprefixUpper)){
cout << inputNumbers[i] <<" hexadecimal "<<" converts to " << inputDecimals[i] <<" decimal\n";
}
}
}catch(exception& e){
cerr << e.what() << endl;
getchar();
}
getchar();
getchar();
return 0;
}
Are there any existent, unknown to me, language facilities that can be used to convert string to number that contains base prefix (0x, 0, i.e. numbers like: 020, 0x16, etc); facilities that recognize number base representation?
I'm trying to make it look more modular and separate it in different functions with a single task (read input, prefix recognition algorithm, print result), any ideas are welcome!
0
is always octal. And it doe snot matter. \$\endgroup\$0x4
is not67
its just4
\$\endgroup\$hex:0, oct:0x
- Hex is0x
and Oct is0
. \$\endgroup\$