Hey guys, this is my first program i have written in C++ tell me what you think!!!
It is a base convertor (yes, i know there is a method that does this, thought it would be good practice.)
Im a intermediate to experienced java programmer, so my first program in C++ was pretty easy. Alot of the syntax is the same, the only thing i dont like about C++ is the way the arrays are setup, so as you can see, i used vectors(instead of lists, for the vector.at()).
Any suggestions for my next C++ program/ comments on this one are much appreciated. Im not much familiar with pointers, i dont really see a point to them, if somebody could explain why i would use a pointer instead of accessing a var directly, that would be great too.
Code:
/*
* @Author - Craig Naumann
* @Date - 5 May, 2010
* @Desc - Converters decimal numbers(base10) to other
* counting systems such as bin(base2) and hex(base16)
*/
#include <string.h>
#include <iostream>
#include <vector>
using namespace std;
vector<int> decToBase(int numb, int base);
vector<char> decToHex(int numb);
vector<int> decToBin(int numb);
int main (){
cout <<"Base Convertor" << endl;
while(true){
vector<int> vect;
int in, conv2;
string conv;
cout <<"Enter a number to change base of: ";
cin >> in;
cout <<"Now enter a base to convert to(bin, hex, other): " ;
cin >> conv;
if(conv != "hex" && conv != "bin" && conv != "other"){
cout << "Invalid selection" << endl;
continue;
}
if(conv == "other"){
cout << "Base to use: ";
cin >> conv2;
}
if(conv == "hex"){
vector<char> vect2 = decToHex(in);
for(int i = 0;i<vect2.size();i++){
cout<< vect2.at(i);
}
cout << endl;
continue;
}else if(conv == ("bin"))
vect = decToBin(in);
else
vect = decToBase(in,conv2);
for(int i = 0;i<vect.size();i++){
cout<< vect.at(i);
}
cout << endl;
}
return 0;
}
vector<char> decToHex(int numb){
vector<int> start = decToBase(numb,16);
vector<char> end;
for(int i = start.size()-1;i>-1;i--){
if(start.at(i)<10){
end.push_back((char)(start.at(i)+48));
}else {
switch(start.at(i)){
case 10:
end.push_back('A');
break;
case 11:
end.push_back('B');
break;
case 12:
end.push_back('C');
break;
case 13:
end.push_back('D');
break;
case 14:
end.push_back('E');
break;
case 15:
end.push_back('F');
break;
}
}
}
return end;
}
vector<int> decToBin(int numb){
vector<int> start = decToBase(numb,2);
vector<int> end;
for(int i = start.size()-1;i>-1;i--){
end.push_back(start.at(i));
}
return end;
}
vector<int> decToBase(int numb, int base){
int rem = 0, dec = numb;
vector<int> compNumb;
do{
rem = dec % base;
dec = dec / base;
compNumb.push_back(rem);
}while(dec != 0);
return compNumb;
}