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?
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?
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 .
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 Source: https://ru.stackoverflow.com/questions/470825/
All Articles
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