Hello!

I have a program that prints the number of digits in it from a string.

Suppose the line "qwrtt56hhbb055ghjj" . Accordingly, the program displays "5 цифр" .

And how can I find their sum now? That is, 5 + 6 + 0 + 5 + 5?

Closed due to the fact that the essence of the issue is incomprehensible by the participants torokhkun , Sergey Rufanov , user194374, Kromster , aleksandr barakin Nov 30, '15 at 18:45 .

Try to write more detailed questions. To get an answer, explain what exactly you see the problem, how to reproduce it, what you want to get as a result, etc. Give an example that clearly demonstrates the problem. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • Code needed - telepaths are not here. - Sergey Rufanov
  • At least in Russian, explain how to write it. I'll write to c ++ myself - Alexey
  • The atoi function converts a string with a number into a number. Further it is already obvious. - Vladimir Martyanov
  • In Russian: every time when the code finds the next digit, add it to the battery (a variable of type int ). Do not forget to initialize the counter, the language will not do it for you. At the end give the value of the battery. - VladD
  • one
    @SergeyRufanov did not specifically write about subtracting from the 0x30 symbol :-) - Vladimir Martyanov

1 answer 1

I think it’s easiest to use regular cycles here.

Here is a demo program that shows two approaches, depending on where the line is stored.

 #include <iostream> #include <string> int main() { { const char *s = "qwrtt56hhbb055ghjj"; unsigned int sum = 0; for ( const char *t = s; *t; ++t ) { if ( *t >= '0' && *t <= '9' ) sum += *t - '0'; } std::cout << "sum = " << sum << std::endl; } { std::string s( "qwrtt56hhbb055ghjj" ); unsigned sum = 0; for ( char c : s ) { if ( c >= '0' && c <= '9' ) sum += c - '0'; } std::cout << "sum = " << sum << std::endl; } return 0; } 

In both cases, the console output will be

 sum = 21 sum = 21