//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;

// Function prototype
bool allDigits(const string &text);

int main()
{
    // DATA DICTIONARY
    // digits  - the string of digits entered by the user
    // 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;
    int sum = 0;
    int highest;
    int lowest;
    unsigned int index;
    int value;

    // Get the digits and reject anything that isn't a digit
    cout << "Enter a series of single-digit numbers "
         << "with nothing between them: ";
    cin >> digits;
    while (!allDigits(digits))
    {
        cout << "Digits only, please. Try again: ";
        cin >> digits;
    }

    // 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;
}

// Returns true if every character in the string is a digit
bool allDigits(const string &text)
{
    unsigned int index;

    for (index = 0; index < text.length(); index++)
    {
        if (!isdigit(text[index]))
            return false;
    }
    return true;
}