Come to think of it. Make a function for everything.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
//supports hex, dec and octal
//base can only equal decimal(10),octal(8),or hex(16)
template<typename ReturnType, typename InputType>
void convertBases(const InputType& src, ReturnType& dest,const int base,bool showBase = true)
{
stringstream stream;
if(showBase)
stream << showbase;
switch(base)
{
case 10: stream << dec; break; /* dec by default but...*/
case 16: stream << hex; break;
case 8: stream << oct; break;
default: throw std::exception("Base not supported"); break;
}
stream << src;
if(!(stream >> dest) ){
string errMsg = "Conversion failed\n";
errMsg += "Tried to convert \"" + string(typeid(src).name());
errMsg += "\" into \"" + string(typeid(dest).name()) + "\"";
throw std::exception(errMsg.c_str());
}
}
int main(){
const int decValue = 15;
enum{ HEX = 16, DEC = 10, OCT = 8 };
string hexValue;
string octalValue;
string deciValue;
try{
convertBases(decValue,hexValue,HEX);
convertBases<string>(decValue,octalValue,OCT);
convertBases<string>(decValue,deciValue,DEC);
}catch(std::exception& e) {
cout << e.what() << endl;
return -1;
}
cout <<"For " << decValue << " : \n";
cout << "hexValue = " << hexValue << endl;
cout << "octalValue = " << octalValue << endl;
cout << "decValue = " << deciValue << endl;
cout << endl;
return 0;
}
Reputation Points: 840
Solved Threads: 594
Senior Poster
Offline 3,859 posts
since Dec 2008