-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ex_05.08.cpp
57 lines (49 loc) · 1.14 KB
/
Ex_05.08.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// read and store a series of integers; print sum of the first N integers
#include "../../../std_lib_facilities.h"
vector<int> numbers;
int getn()
{
double n;
cout << "Enter the number of values you want to sum:\n";
while (!(cin >> n) || floor(n)!=ceil(n) || n < 1) {
cout << "Please enter an integer greater than 0:\n";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return int(n);
}
void getnum()
{
double input;
cout << "Please enter some integers (enter any non-number to stop):\n";
while (cin >> input) numbers.push_back(narrow_cast<int>(input));
return;
}
void printsum(int n)
{
int sum = 0;
if (numbers.size() < n)
error("Not enough numbers to sum!");
else
for (int i = 0; i < n; ++i)
sum += numbers[i];
cout << "Sum of the first " << n << " integers is " << sum << '\n';
return;
}
int main()
try {
int n = getn();
getnum();
printsum(n);
return 0;
}
catch (runtime_error& e) {
cerr << "Error: " << e.what() << '\n';
keep_window_open();
return 1;
}
catch (...) {
cerr << "Error: Unknown exception" << '\n';
keep_window_open();
return 2;
}