fork download
  1. //Ryan Shahriyarpour CS1A Chapter 10 Question 8
  2. /*****************************************************************************
  3.  *
  4.  * Sum of Digits in a String
  5.  *
  6.  *********************
  7.  *
  8.  * This program asks the user to enter a series of single-digit numbers with
  9.  * nothing separating them. The input is read as a string object. The program
  10.  * displays the sum of all the digits, along with the highest and lowest
  11.  * digits in the string.
  12.  * For example, if the user enters 2514 the sum is 12, the highest digit
  13.  * is 5, and the lowest digit is 1.
  14.  *
  15.  * INPUT
  16.  * digits - a string of single-digit numbers with no separators
  17.  *
  18.  * OUTPUT
  19.  * The sum, highest digit, and lowest digit
  20.  *
  21.  ****************************************************************************/
  22.  
  23. #include <iostream>
  24. #include <string>
  25. #include <cctype>
  26. using namespace std;
  27.  
  28. int main()
  29. {
  30. // DATA DICTIONARY
  31. // digits - the string of digits entered by the user
  32. // valid - true if every character entered is a digit
  33. // sum - the sum of all the digits
  34. // highest - the largest digit found
  35. // lowest - the smallest digit found
  36. // index - loop counter
  37. // value - numeric value of the digit being examined
  38. string digits;
  39. bool valid = true;
  40. int sum = 0;
  41. int highest = 0;
  42. int lowest = 0;
  43. unsigned int index = 0;
  44. int value = 0;
  45.  
  46. // Get the digits
  47. cout << "Enter a series of single-digit numbers "
  48. << "with nothing between them: ";
  49. cin >> digits;
  50.  
  51. // Reject anything that isn't a digit and ask again
  52. do
  53. {
  54. valid = true;
  55. for (index = 0; index < digits.length(); index++)
  56. {
  57. if (!isdigit(digits[index]))
  58. valid = false;
  59. }
  60. if (!valid)
  61. {
  62. cout << "Digits only, please. Try again: ";
  63. cin >> digits;
  64. }
  65. } while (!valid);
  66.  
  67. // Start the highest and lowest at the first digit
  68. highest = digits[0] - '0';
  69. lowest = digits[0] - '0';
  70.  
  71. // Total the digits and track the highest and lowest
  72. for (index = 0; index < digits.length(); index++)
  73. {
  74. value = digits[index] - '0';
  75. sum += value;
  76.  
  77. if (value > highest)
  78. highest = value;
  79. if (value < lowest)
  80. lowest = value;
  81. }
  82.  
  83. // Display the results
  84. cout << "\nSum of the digits: " << sum << endl;
  85. cout << "Highest digit: " << highest << endl;
  86. cout << "Lowest digit: " << lowest << endl;
  87.  
  88. return 0;
  89. }
Success #stdin #stdout 0s 544KB
stdin
1524
stdout
Enter a series of single-digit numbers with nothing between them: 
Sum of the digits: 12
Highest digit:     5
Lowest digit:      1