sum of integer range [no doubles]

Bjarne Stroustrup “Programming Principles and Practice Using C++”
Chapter 5 Exercise 9
Using std_lib_facilities.h by Bjarne Stroustrup.

//	Philipp Siedler
//	Bjarne Stroustrup's PP
//	Chapter 5 Exercise 9

//input: 3
//input: 1.2 4 3.2 5x

#include "std_lib_facilities.h"

int main()
try
{
	vector<double> numVec;

	int numCount = 0;
	double value;
	double numSum = 0;
	string check;

	cout << "Enter number of integers to be read:\n";
	if (cin >> numCount) {}
	else {
		cin.clear();
		cin >> check;
		error("Entered value does not match: ", check);
	}

	cout << "Enter some values to be stored seperated by a blank space "
		"ending with a 'x': \n";
	for (int i = 0; i < numCount; i++) {
		if (cin >> value) {
			numVec.push_back(value);
			numSum += value;
		}
		else {
			cin.clear();
			cin >> check;
			if (check == "x") {
				break;
			}
			else {
				error("Input is no value: ", check);
			}
		}
	}

	if (numVec.size() < numCount) {
		error("The entered number of integers to be read is larger than the vector size.\n");
	}

	for (int i = 0; i < numVec.size(); i++) {
		cout << numVec[i] << "\n";
	}

	int numSum_int = numSum;
	double numSum_check = numSum - numSum_int;

	if (numSum_check > 0.0) {
		cout << "unfortunately the sum cannot be written as integer" << "\n";
	}
	else {
		cout << "sum = " << numSum << "\n";
	}

	keep_window_open(".");
}

catch (runtime_error e) {
	cout << e.what() << "\n";
	keep_window_open(".");
}
catch (...) {
	cout << "Extiting" << "\n";
	keep_window_open(".");
}
Output:
Enter number of integers to be read:
3
Enter some values to be stored seperated by a blank space ending with a 'x':
1.2 4 3.2 5x
1.2
4
3.2
unfortunately the sum cannot be written as integer
Please enter . to exit

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.