Having trouble with getting a correct value from my return function

Hi, I am having trouble with getting the correct return value from the function I have typed. The value seems to be larger than what it's supposed to be (like it's multiplied by 10?) I think it has to do with the return part of my code, I think I may be using the wrong value type. I am really new to coding so i've been really struggling with identifying the problem. In my main function I obtain a string message of numbers from the user, and then those numbers are used in the function shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int sumOfDoubleDigits(const string& creditNumber) {
	int sum = 0;   
	if (creditNumber.size() == 13 || creditNumber.size() == 15) {
		for (int i = 0; i < creditNumber.size(); i += 2) {
			sum += creditNumber.at(i); 
		}
	}
	else if (creditNumber.size() == 14 || creditNumber.size() == 16) {
		for (int i = 1; i < creditNumber.size(); i += 2) {
			sum += creditNumber.at(i);
		}
	}
	return sum; 
}
Looks like you are summing the ASCII values of the chars, consider converting them to digits.

Also consider using a debugger, one can deduce solutions.
Be aware that string::at() gives you the character at the specified position of the string. It does not convert that character into a "numeric" value though!

So, assuming the string is encoded in ASCII, you are adding up the ASCII codes of those characters. The ASCII code of '0' is 0x30 (or 48 in decimal). The ASCII code of '1' is 0x31 (or 49 in decimal). And so on...

See also:
https://en.wikipedia.org/wiki/ASCII#Printable_characters


Try changing:
sum += creditNumber.at(i);
...into:
sum += (int)creditNumber.at(i) - 0x30;

This converts ASCII codes into the equivalent "numeric" value. Of course, it only works correctly, if all characters in the string are in the '0' (0x30) to '9' (0x39) range. For other characters, e.g. 'A' or '$', it breaks!


Another option would be:
sum += atoi(creditNumber.substr(i,1).c_str());
Last edited on
that makes so much more sense! I can't believe i didn't notice that i was adding ascii codes loll. thank you so much! I've spent the last couple hours rewriting my loops hahah. i really appreciate it.
Topic archived. No new replies allowed.