forked from SailmakerLock/Lossless-Scaling-Desktop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.cpp
More file actions
101 lines (90 loc) · 2.79 KB
/
Main.cpp
File metadata and controls
101 lines (90 loc) · 2.79 KB
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
92
93
94
95
96
97
98
99
100
101
#include <iostream>
#include <stdexcept>
#include <limits>
/**
* @brief Simple console calculator supporting basic arithmetic operations.
* Handles user input and performs calculations with error checking.
*/
class SimpleCalculator {
public:
/**
* @brief Performs arithmetic operation based on provided operator and operands.
* @param a First operand
* @param b Second operand
* @param op Operator (+, -, *, /)
* @return Result of the operation
* @throws std::invalid_argument for invalid operators or division by zero
*/
static double calculate(double a, double b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0) {
throw std::invalid_argument("Error: Division by zero is not allowed.");
}
return a / b;
default:
throw std::invalid_argument("Error: Unsupported operator. Use +, -, *, or /.");
}
}
};
/**
* @brief Safely reads a double value from user input with error handling.
* @param prompt Message to display to the user
* @return Valid double number
*/
double getNumber(const std::string& prompt) {
double value;
while (true) {
std::cout << prompt;
if (std::cin >> value) {
return value;
} else {
std::cin.clear(); // Clear error flags
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '
');
std::cout << "Invalid input. Please enter a valid number.
";
}
}
}
/**
* @brief Main function — entry point of the program.
* Runs the calculator loop until user chooses to exit.
*/
int main() {
std::cout << "=== Simple Calculator ===
";
std::cout << "Supported operations: +, -, *, /
";
char continueChoice;
do {
// Get user input
double num1 = getNumber("Enter first number: ");
double num2 = getNumber("Enter second number: ");
char op;
std::cout << "Enter operator (+, -, *, /): ";
std::cin >> op;
try {
double result = SimpleCalculator::calculate(num1, num2, op);
std::cout << "Result: " << num1 << " " << op << " " << num2 << " = " << result << "
";
} catch (const std::invalid_argument& e) {
std::cout << e.what() << "
";
}
std::cout << "Do you want to perform another calculation? (y/n): ";
std::cin >> continueChoice;
// Clear input buffer
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '
');
} while (continueChoice == 'y' || continueChoice == 'Y');
std::cout << "Calculator terminated. Goodbye!
";
return 0;
}