for loop

Wrote a program to add the digits of an integer, program is right except for the fact that it adds 48 to each loop... I'm not sure why. I've printed the individual values of temp and sum and they will correspond correctly but then when added the 48 gets added, no idea why. Hopefully fresh eyes can see it, it's inside the sumOfDigits function.

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

#include <iostream>
#include <string>
#include <cmath>


int sumOfDigits(int x, int size);

int main(int argc, const char * argv[]) {
    
    int x;
    std::cout << "Give me an integer: ";
    std::cin >> x;
    std::string s = std::to_string(x);
    int size = s.size();
    int y = sumOfDigits(x, size);
    std::cout << "Sum of integer " << x << "'s digits is: " << y;
    
    return 0;
}
  int sumOfDigits(int x, int size)
{
    int sum = 0;
    std::string s = std::to_string(x);
    for (int i = 0; i < size; i++)
    {
        int temp = s.at(i);
        sum = temp + sum;
        //have no idea why the program doesn't work without this line
        sum -= 48;
    }
    return sum;
}
Last edited on
48 is the integer value of character '0'.
s.at(i) will give a value of type 'char' that is to be interpreted as a symbol. For example, the symbol for the digit '0' is not equal to the value 0. Symbols are usually encoded according to ASCII encoding, where '0' is encoded as 48, '1' is encoded as 49, 'A' is encoded as 65 etc look it up on wikipedia.

So you need something like:

int temp = s.at(i) - '0'; //'0' usually equals 48, on most computers.

Also note that your way of extracting digits form the integer is not quite the usual one, but it is kind of creative...
If it makes you feel better, the way how C++ converts chars to integers is a leftover from C language... and, perhaps, from a high-level perspective, not quite the best choice for a modern languge. But you have to understand the C language designers, in those days hard drives were the size of a washing machine...
Topic archived. No new replies allowed.