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. // Function prototype
  29. bool allDigits(const string &text);
  30.  
  31. int main()
  32. {
  33. // DATA DICTIONARY
  34. // digits - the string of digits entered by the user
  35. // sum - the sum of all the digits
  36. // highest - the largest digit found
  37. // lowest - the smallest digit found
  38. // index - loop counter
  39. // value - numeric value of the digit being examined
  40. string digits;
  41. int sum = 0;
  42. int highest;
  43. int lowest;
  44. unsigned int index;
  45. int value;
  46.  
  47. // Get the digits and reject anything that isn't a digit
  48. cout << "Enter a series of single-digit numbers "
  49. << "with nothing between them: ";
  50. cin >> digits;
  51. while (!allDigits(digits))
  52. {
  53. cout << "Digits only, please. Try again: ";
  54. cin >> digits;
  55. }
  56.  
  57. // Start the highest and lowest at the first digit
  58. highest = digits[0] - '0';
  59. lowest = digits[0] - '0';
  60.  
  61. // Total the digits and track the highest and lowest
  62. for (index = 0; index < digits.length(); index++)
  63. {
  64. value = digits[index] - '0';
  65. sum += value;
  66.  
  67. if (value > highest)
  68. highest = value;
  69. if (value < lowest)
  70. lowest = value;
  71. }
  72.  
  73. // Display the results
  74. cout << "\nSum of the digits: " << sum << endl;
  75. cout << "Highest digit: " << highest << endl;
  76. cout << "Lowest digit: " << lowest << endl;
  77.  
  78. return 0;
  79. }
  80.  
  81. // Returns true if every character in the string is a digit
  82. bool allDigits(const string &text)
  83. {
  84. unsigned int index;
  85.  
  86. for (index = 0; index < text.length(); index++)
  87. {
  88. if (!isdigit(text[index]))
  89. return false;
  90. }
  91. return true;
  92. }
Success #stdin #stdout 0s 544KB
stdin
1246
stdout
Enter a series of single-digit numbers with nothing between them: 
Sum of the digits: 13
Highest digit:     6
Lowest digit:      1