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
|
#include <iostream>
#include <algorithm>
#include <string>
double getNum(const std::string& promp) {
double no {};
while ((std::cout << promp) && !(std::cin >> no)) {
std::cout << "Invalid number\n";
std::cin.clear();
std::cin.ignore(1000, '\n');
}
return no;
}
int main()
{
enum class Opers { Quit = 0, Add, Subtract, Multiply, Divide };
struct s_ops {
std::string name;
Opers op;
};
const s_ops Ops[] {{"quit", Opers::Quit}, { "add", Opers::Add }, {"subtract", Opers::Subtract}, {"multiply", Opers::Multiply}, {"divide", Opers::Divide}};
double next {}, sum {getNum("Enter first number: ")};
std::string oper;
auto fnd {std::begin(Ops)};
do {
do {
std::cout << "Enter operator as a word (";
for (const auto& o : Ops)
std::cout << o.name << ' ';
std::cout << "): ";
std::cin >> oper;
fnd = std::find_if(std::begin(Ops), std::end(Ops), [&oper](const auto& i) {return i.name == oper; });
if (fnd != std::end(Ops)) break;
else
std::cout << "Invalid operator name entered\n";
} while (true);
if (fnd->op != Opers::Quit) {
next = getNum("Enter next number: ");
switch (fnd->op) {
case Opers::Add: sum += next; break;
case Opers::Subtract: sum -= next; break;
case Opers::Multiply: sum *= next; break;
case Opers::Divide: sum /= next; break;
}
std::cout << "Result is " << sum << '\n';
} else break;
} while (true);
}
| |