
//
// This is example code from Chapter 5.11 "Drill" of
// "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup
//
/***8. Write a program that reads and stores a series of integers and then computes the sum
of the first N integers. First ask for N, then read the values into a vector, then
calculate the sum of the first N values. For example:
“Please enter the number of values you want to sum:”
3
“Please enter some integers (press '|' to stop):”
12 23 13 24 15 |
“The sum of the first 3 numbers ( 12 23 13 ) is 48.”
Handle all inputs. For example, make sure to give an error message if the user asks for a sum of
more numbers than there are in the vector.

9. Modify the program from exercise 8 to write out an error if the result cannot be represented as
an int.
**/

#include "..\std_lib_facilities.h"

//------------------------------------------------------------------------------
double sumOfN(vector<int> vi, int N) { /// converts Celsius to Fahrenheit
    int sum = 0;
    for(int i = 0; i < N; ++i)
        sum += vi[i];
    return sum;
}

int main()
try {
    vector<int> vi;
    int x, N=5;
    cout << "\nEnter a bunch of integers, -1 to quit: ";
    cin >> x;
    do {
        vi.push_back(x);
        cin >> x;
        if(x!=int(x)) error("Not an int.");
    } while(x != -1);
    cin.clear();
    cout << "\nHow many of these would you like to add? ";
    cin >> N;
    if(N>vi.size()) error("You asked for too much.");
    cout << "\nThat's " << sumOfN(vi, N);
    return 0;
}

catch (exception& e) {
    cerr << "error: " << e.what() << '\n';
    keep_window_open();
    return 1;
}
catch (...) {
    cerr << "Oops: unknown exception!\n";
    keep_window_open();
    return 2;
}

//------------------------------------------------------------------------------

