CPP Übung

Aus “Programming: Principles and Practice Using C++”

 Exercise is to first define the amount of numbers n beginning from the first
 to n in a vector, enter a random set of integer values to a vector and then
 sum the amount of n values. Checks to prevent out of range errors must be implemented.

#include "std_lib_facilities.h"

using namespace std;
void checkvecsize (unsigned long vecsize, int n)
    if (n>vecsize)
        error("Youw ant to sum more value than are available!\n"); // Check if vector size is enough.

int main ()
    int n;
    cout << "Please enter the number of values:\n";
    cin >> n;
    bool stop = 0; // to keep the while loop going until told otherwise
    vector<int> numbers;
    int values{};
    int sum = 0;
    string value_check;
    cout << "Please enter a couple of number. Press s to stop! \n";
            cin >> value_check;
            if (value_check=="s")  // by pressing s the while loop stops.
                stop = 1;
                error("Use only numbers or (s) to stop");
    checkvecsize(numbers.size(), n);
    for (int i=0; i<n; i++)
        sum = sum + numbers[i];
    cout << "The sum of the first " << n << " values = " << sum << "!\n";
catch(runtime_error e)
    cout << e.what() << '\n';
catch (...)
    cout << "Exiting with unknown error" << '\n';