fork download
  1.  
  2. //Dione Torrevillas CS1A Chapter 10, P. 589, #8
  3. /******************************************************************************
  4.  * SUM OF DIGITS IN A STRING
  5.  * This program accepts a series of digits and displays their
  6.  * sum, highest digit, and lowest digit.
  7.  *
  8.  * INPUT:
  9.  * numbers : String of digits entered by the user
  10.  *
  11.  * OUTPUT:
  12.  * sum : Sum of all digits
  13.  * highest : Highest digit
  14.  * lowest : Lowest digit
  15.  ******************************************************************************/
  16. #include <iostream>
  17. #include <string>
  18. using namespace std;
  19.  
  20. int main()
  21. {
  22. string numbers;
  23. int sum = 0, highest = 0, lowest = 9;
  24. int digit;
  25.  
  26. // Get a string of digits from the user.
  27. cout << "Enter a series of digits: ";
  28. getline(cin, numbers);
  29.  
  30. // Check for an empty string.
  31. if (numbers.empty())
  32. {
  33. cout << "No digits were entered." << endl;
  34. return 0;
  35. }
  36.  
  37. // Process each digit in the string.
  38. for (int count = 0; count < static_cast<int>(numbers.length()); count++)
  39. {
  40. // Make sure the character is a digit.
  41. if (numbers[count] < '0' || numbers[count] > '9')
  42. {
  43. cout << "Please enter digits only." << endl;
  44. return 0;
  45. }
  46.  
  47. // Convert the character to an integer.
  48. digit = numbers[count] - '0';
  49. sum += digit;
  50.  
  51. // Find the highest and lowest digits.
  52. if (digit > highest)
  53. highest = digit;
  54.  
  55. if (digit < lowest)
  56. lowest = digit;
  57. }
  58.  
  59. // Display the results.
  60. cout << "Sum of digits: " << sum << endl;
  61. cout << "Highest digit: " << highest << endl;
  62. cout << "Lowest digit: " << lowest << endl;
  63.  
  64. return 0;
  65. }
  66.  
Success #stdin #stdout 0s 544KB
stdin
2514
stdout
Enter a series of digits: Sum of digits: 12
Highest digit: 5
Lowest digit: 1