Trying to write a base converter
Jul 4, 2009 at 12:13am UTC
I'm trying to write a base converter that allows the user to convert any number from base x to base y (2-16).
It will also allow for hexadecimal conversion. This is where I'm running into problems.
I'm trying to figure out how to discard any erroneous input (i.e. characters 'G' - 'Z' ) as they shouldn't be converted to hex since they are not within the normal hex range 'A' - 'F'.
Here is the code I've written below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
char numIn[15];
int num[15];
char values[17] = "0123456789ABCDEF" ; // array used for table lookup
int ob, nb, i;
cout << "Enter the the number you want to convert: " ;
cin >> numIn;
// convert string to upper case
strupr(numIn);
cout << "Enter the original base (2-16): " ;
cin >> ob;
//bool checkValue(char numIn){
// if(numIn < 0 || numIn > 9){
// if(numIn < 'a' || numIn > 'f'){
// cout << "omg error";
// return false;
// }
// }
//}
// range checking
while (ob < 2 || ob > 16)
{
cout << "Base isn't 2-16. Please re-enter: " << endl;
cin >> ob;
}
cout << "Enter the new base (2-16): " ;
cin >> nb;
// range checking
while (nb < 2 || nb > 16)
{
cout << "Base isn't 2-16. Please re-enter: " << endl;
cin >> nb;
}
// find the string length for the loop
int length = strlen(numIn);
cout << "The length of the string is: " << length << endl;
// reverse the string for later use
strrev (numIn); // this reverses the string
cout << "After reversing the string, the string is: " ;
for (i = length - 1; i >= 0; i--)
{
cout << numIn[i];
}
cout << endl;
// loop through each subscript of the input
for (i=0; i < length; i++)
{
// check to see if it's a letter or number
if (isdigit(numIn[i]))
{
num[i] = numIn[i] - 48;
}
else
{
num[i] = numIn[i] - 55;
}
cout << num[i] << " " ;
}
return 0;
}
Any help or assistance in the right direction would be greatly appreciated.
Jul 4, 2009 at 12:39am UTC
Create a function that takes an array of chars, then goes through and makes sure everything in the array is within the correct values...here is an example to make sure everything is a number [1-5]:
1 2 3 4 5 6
bool checkString(char * String, unsigned int size) {
for (unsigned int i = 0; i < size; ++i) {
if (String[i] < '1' && String[i] > '5' ) return false ;
}
return true ;
}
Jul 4, 2009 at 2:24am UTC
I am so confused right now. So I'll declare this above the main program and call it when the user is prompted to enter in their numbers?
Jul 4, 2009 at 4:06am UTC
Topic archived. No new replies allowed.