string str = "4fd8bfb78d5291eb809d0beab33acf4ae505e1df"; const char * cstr = str.c_str(); stringstream std; int summ = 0; for(unsigned int i=0; strlen(cstr) > i; i++) { std << cstr[i]; summ += atoi(std.str().c_str()); std.str(""); } 

The meaning of the code I think is clear, wondering how you can implement more adequately ...

  • If you don’t want to write a cycle with hands, then std::accumulate( str.c_str(), str.c_str() + str.size(), 0, [](size_t sz, char c){ return sz + (c - '0'); } ); function, of course, you need to file so that the letters are correctly processed - fogbit

1 answer 1

If I correctly understood your code, then your task is to calculate the sum of digits in a line. This is done much easier:

 for (unsigned int i = 0; i < strlen(cstr); i++) { if (cstr[i] >= '0' && cstr[i] <= '9') { summ += cstr[i] - '0'; } } 

Read about ASCII and character codes. If your task was to calculate the sum of all numbers in a string, then the code will become a bit more complicated, but the principle will remain similar.

  • Thanks a lot. - avengerweb
  • 2
    And in order not to call strlen at each iteration, you can file it like this: instead of the condition i <strlen (cstr), write cstr [i] in a loop. - paulgri
  • 3
    @paulgri: or at least cache the value of strlen . - VladD