Calculator for Stroustrup's Book - Chapter 3 Exercise

I wrote this calculator code and it's working fine, but I wanted to ask if I'm doing the error-handling fine or not. As it is now, the program will exit immediately after the exception handling code is done, but I'm wondering if that's fine for this program. [Note: as of Chapter 3, exceptions still haven't been introduced yet, but I already know about them so I decided to use them.]

Here's the code:
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
// chap3_ex10.cpp : Defines the entry point for the console application.
// Osman Zakir
// 5 / 24 / 2016
// Programming: Principles and Practice using C++ 2nd Edition Chapter 3 Exercise 10
// This is a very simple calculator. Only accepts one operation and two numbers

#include "std_lib_facilities.h"

double get_number();
string get_operaton();
double calculate_result(const double x, const double y, const string& operation);
void print_result(const double result);

int main()
{
	try
	{
		cout << "Enter a number: ";
		double x = get_number();
		cout << "Enter another number: ";
		double y = get_number();
		cout << "Enter an operation: ";
		string operation = get_operaton();
		double result = calculate_result(x, y, operation);
		print_result(result);
		keep_window_open();
	}
	catch (const runtime_error& r)
	{
		cerr << r.what() << "\n";
		keep_window_open();
		return 1;
	}
	catch (const exception& e)
	{
		cerr << e.what() << "\n";
		keep_window_open();
		return 2;
	}
	catch (...)
	{
		cerr << "Error: Unexpected exception caught\n";
		keep_window_open();
		return 3;
	}
}

double get_number()
{
	double number = 0;
	cin >> number;
	cin.ignore(32767, '\n');
	return number;
}

string get_operaton()
{
	string operation;
	cin >> operation;
	cin.ignore(32767, '\n');
	return operation;
}

double calculate_result(const double x, const double y, const string& operation)
{
	if (operation == "+")
	{
		return x + y;
	}
	else if (operation == "-")
	{
		return x - y;
	}
	else if (operation == "*")
	{
		return x * y;
	}
	else if (operation == "/")
	{
		return x / y;
	}
	else if (operation != "/" || operation != "*" || operation != "+" || operation != "-")
	{
		error("Invalid operation!");
	}
}

void print_result(const double result)
{
	cout << "Your answer is: " << result << "\n";
}


The library access header for the book, std_lib_facilities.h, has iostream and stdexcept, as well as the file that defines std::numeric_limits, among other important header files. I could bring it here for anyone who needs it, but this post is already going to get too long so I'll have to do that in another post.
Last edited on
Topic archived. No new replies allowed.