• Forum
  • Jobs
  • to get sum of digits, skip the alphabets

 
to get sum of digits, skip the alphabets..

Prompt the user to input a string,
and then output the sum of all the digits in the string.

Sample Run 1:

Input -> A111B222C
9

Sample Run 2:

Input -> ABC123XYZ32100000005555555555zzzzzz
62
===========================================
can anyone show me the simple coding..
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
std::string s;

std::cout << "Enter a string: ";
std::cin >> s;

int sum = 0;

for ( char c : s ) 
{
   if ( std::isdigit( c ) ) sum += c - '0';
}

std::cout << "sum = " << sum << std::endl;


The same can be done with standard algorithm std::accumulate.
If you use MS VC++ 2010 you should change

for ( char c : s )

to

for each ( char c in s )
Topic archived. No new replies allowed.