need help with a program

Okay, so I have an assignment, and I have been breaking my head for days can't figure it out.

The idea is to creat a program that reads numbers from a file, hexadecimal, and converts them into decimal, adds them and prints the decimal sum of the numbers.
Can't figure out how to read the hexadecimal number and actually do something with them. I tried reading them into a char array, seperated by commas, or by new lines, and I can't figure out what to do to read them and convert them into decimal.

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
  #include <iostream>
#include <fstream>
#include <iomanip>
#include <cmath>
#include <string>
#include <cstdlib>

using namespace std;


int main()
{
	char hexVal[50];
	int deciVal;
	int deciArr[5];
	int allChar = 0;
	int temp = 0;
	int j = 0;


	ifstream hexaFile;
	hexaFile.open("D:\\Project\\Visual Studios\\Hex to Deci\\hexa.txt");
	if (!hexaFile)
	{
		cout << "Error opening file" << endl;
	}


	while (!hexaFile.eof())
	{
		hexaFile >> hexVal[allChar];
		allChar++;

	
	}
	
	for (int i = allChar - 2; i > 0 - 1; i--)
	{
		while (hexVal[i] != ',')
		{
			
		}
	}

		system("pause");
		return 0;
	}


This is pretty much what I got right now in a nutshell, a lot of trial and error , have no idea.
Could you please guide me towards the right direction or explain how can I read them so I can add them into a decimal value?
Thanks in advance.
It's easier if you separate the values by whitespace character such as newline, tab or space. Then you don't need to handle commas in your program.

To read an integer in hexadecimal format you can use std::hex.

hexaFile >> std::hex >> hexVal[allChar];
http://www.cplusplus.com/reference/ios/hex/
Do I have to ue the
std::hex
While I do the math? I mean, I can get the Value "2F1" into an integer, or an array and then add it just like that:
deciSum =+ hexVal[i]
(say I have a for loop with the array holding the hex values)

Thanks.
No you use the integer value just like normal. Hex is only relevant when you convert from/to text.
Last edited on
Thanks a lot!
Topic archived. No new replies allowed.