fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4.  
  5. // Sum the characters in a c-style string.
  6. int cStringSum( const char * str )
  7. {
  8. int sum = 0;
  9. // Loop while we haven't hit the terminating '\0' char.
  10. while ( '\0' != *str )
  11. {
  12. // Add the current char to the sum.
  13. sum += *str;
  14. ++str;
  15. }
  16. return sum;
  17. }
  18.  
  19. // Sum the characters in a c++ string.
  20. int stringSum( const std::string & str )
  21. {
  22. int lim = str.size();
  23. int sum = 0;
  24. // Use a normal loop over the number of characters.
  25. for ( int pos = 0; pos < lim; ++pos )
  26. {
  27. // Add the current char to the sum.
  28. sum += str[pos];
  29. }
  30. return sum;
  31. }
  32.  
  33. int main()
  34. {
  35. // For decimal output.
  36. std::cout << cStringSum("abc") << "\n";
  37. std::cout << stringSum("abc") << "\n";
  38.  
  39. // For hex output.
  40. std::cout << std::hex;
  41. std::cout << cStringSum("abc") << "\n";
  42. std::cout << stringSum("abc") << "\n";
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0.01s 2812KB
stdin
Standard input is empty
stdout
294
294
126
126