Adding all the digits into a string.

I wrote a program to find the numbers into a string and calculate the sum of all the found numbers.

Here is my program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <string>
#include <cctype>

using namespace std;

int main()
{
    string s="a1b2b3cc4";

    int sum=0;

    for(int i=0; i<s.length(); i++)
    {
        if(isdigit(s[i]))
            sum+=s[i];
    }

    cout<<sum;

    return 0;
}


The output should be = 10 but it shows 202 as output.

But If I write

1
2
if(isdigit(s[i]))
   cout<<s[i];


it prints 1 2 3 4..which is okay.

Why its doing like this? How is it working?
Because you are adding character to an in teger. characeter '1' is not equal to integer 1.
You want to convert character to "proper" integer first. If all you care is standard PC, this will do this for you: sum += s[i] - '0';
Topic archived. No new replies allowed.