School Code, Base Conversions

Hi everyone, this is my first post on this forum. I am currently writing a program that takes an integer in either base 2, 10, or 16 and converts it into base 10 integer. Everything was going swell, until my teacher told us that we have to implement the base 16 to base 10 conversions in the form of an array. I am having difficulty doing this. Help would be appreciated. Thank You!

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
#include "stdafx.h"
#include <iostream>
using namespace std;
int getanint(int base)
{
	char c;
	int i=0;
	int j=0;
	int foo[];

	cout<<"What number do you want to convert to base 10?"<<endl;
	cin.get(c);
	if (c=='\n')
		cin.get(c);
	//this if statement was needed for my compiler, as when I pressed 'enter', it took is at a separate character

	while((c<='9' && c>='0')||(c<='F' && c>='A'))
	{
	//the first part of the while is for bases 2-9, and the other one is 	for 10-16
		i=(base*j);
		//this was required for either of the two below functions, so I made it separate

		if(c<='9' && c>='0')
		{
			j=(i+c-'0');
		//this is the function for bases 2-9
		}
		else
		{
			j=(i+c-'A'+10);
		//this is the function for base 16. The problem here is that I need to use an array instead of the algorithm. I think that the character entered by the user is the one supposed to be used as the index.
		}
		cin.get(c);
		//cin.get takes the string one character at a time, so I put it at the bottom here
	}
	return j;
	//j is the result that I want to print
}

int main(void)
{
	int base;
	cout<<"What base will you use? You must choose between 2,10 or 16."<<endl;
	cin>>base;
	cout<<getanint(base);
	system("pause");
	return 0;
}

Try this:

Declare this array in getanint() or in main or whatever:
char digits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

Then use this function to process the input:
1
2
3
4
5
6
7
8
9
10
//gets index if c is in array, else returns -1
int getIndex (char arr[], int len, char c) {
	int i = 0;
	for (; i<len; i++) {
		if (arr[i] == c) { 
			return i; 
		}
	}
	return -1;
}


Might want to check after you use getIndex() that the result isn't -1 or higher than base-1.

Also, I really like line 20. Had to mentally step through the code to see how were getting positions right.
Topic archived. No new replies allowed.