//Ryan Shahriyarpour   CS1A  Chapter 10   Question 8
/*****************************************************************************
 *
 * Sum of Digits in a String
 *
 *********************
 *
 * This program asks the user to enter a series of single-digit numbers with
 * nothing separating them. The input is read as a string object. The program
 * displays the sum of all the digits, along with the highest and lowest
 * digits in the string.
 * For example, if the user enters 2514 the sum is 12, the highest digit
 * is 5, and the lowest digit is 1.
 *
 * INPUT
 *  digits - a string of single-digit numbers with no separators
 *
 * OUTPUT
 *  The sum, highest digit, and lowest digit
 *
 ****************************************************************************/

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main()
{
    // DATA DICTIONARY
    // digits  - the string of digits entered by the user
    // valid   - true if every character entered is a digit
    // sum     - the sum of all the digits
    // highest - the largest digit found
    // lowest  - the smallest digit found
    // index   - loop counter
    // value   - numeric value of the digit being examined
    string digits;
    bool valid = true;
    int sum = 0;
    int highest = 0;
    int lowest = 0;
    unsigned int index = 0;
    int value = 0;

    // Get the digits
    cout << "Enter a series of single-digit numbers "
         << "with nothing between them: ";
    cin >> digits;

    // Reject anything that isn't a digit and ask again
    do
    {
        valid = true;
        for (index = 0; index < digits.length(); index++)
        {
            if (!isdigit(digits[index]))
                valid = false;
        }
        if (!valid)
        {
            cout << "Digits only, please. Try again: ";
            cin >> digits;
        }
    } while (!valid);

    // Start the highest and lowest at the first digit
    highest = digits[0] - '0';
    lowest = digits[0] - '0';

    // Total the digits and track the highest and lowest
    for (index = 0; index < digits.length(); index++)
    {
        value = digits[index] - '0';
        sum += value;

        if (value > highest)
            highest = value;
        if (value < lowest)
            lowest = value;
    }

    // Display the results
    cout << "\nSum of the digits: " << sum << endl;
    cout << "Highest digit:     " << highest << endl;
    cout << "Lowest digit:      " << lowest << endl;

    return 0;
}