2

I am trying to add all the digits of a string in c++, but it cannot passes all test cases. My code is given below.

 #include <iostream>
using namespace std;

int main()
{
    string str;
    long long int count=0;
    cin>>str;
    for(int i=0;i<str.length();i++)
    {
        count+=(str[i]-'0');
    }
    cout<<count<<endl;
    return 0;
}

Don't know how to resolve this problem can anyone help me out???

2 Answers2

1

You can try this

#include <iostream>
using namespace std;

int main()
{
    string str;
    long long int count=0;
    cin>>str;
    //ASCII value of digits 0-9 lie between 48 to 57
    for(int i=0;i<str.length();i++)
    {
        if(str[i]>=48 && str[i]<=57)
            count = count + (int)str[i] - 48;
    }
    cout<<count<<endl;
    return 0;
}
0

Code shown works correctly for strings that contains only digits (like "123").

There are two more cases that may need to be handled - non-digits and non-ASCII digits (this is less likely for beginner assignment).

One way to handle non-digits is to convert them to zero using conditional operator (also known as "ternary operator")

count += isdigit(str[i]) ? (str[i]-'0') : 0;

For second case if your program must support all Unicode numerals like “¼” you would need to either find library that supports full Unicode tables or write special cases yourself. Note that you'd need result to be float as not all numerals represent whole numbers.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179