-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcalculator_utils.cpp
75 lines (60 loc) · 2.1 KB
/
calculator_utils.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "calculator_utils.h"
#include <thread>
bool CalculatorUtils::is_digit(const std::string& s){
auto it = s.begin();
while (it != s.end() && (std::isdigit(*it) || *it == '.')) ++it;
return !s.empty() && it == s.end();
}
bool CalculatorUtils::is_valid_operator_or_digit(const std::string& s) {
return is_digit(s) || is_valid_operator(s);
}
bool CalculatorUtils::is_valid_operator_or_digit(const char& s) {
return isdigit(s) || is_valid_operator(s) || s == '.';
}
inline bool CalculatorUtils::is_valid_operator(const std::string& s) {
return s == "+" || s == "-" || s == "*" || s == "/" || s == "%" || s == "^";
}
inline bool CalculatorUtils::is_valid_operator(const char& s) {
return s == '+' || s == '-' || s == '*' || s == '/' || s == '%' || s == '^';
}
bool CalculatorUtils::has_repeated_operators(const std::string& s) {
const auto begin = s.begin();
const auto end = s.end();
if (s.length() < 2) return false;
for (auto it = begin + 1; it != end; ++it) {
if (isdigit(*it)) continue;
if (*it == '(' || *it == ')') continue;
if (is_valid_operator(*it) && is_valid_operator(*(it - 1))) {
return true;
}
}
return false;
}
bool CalculatorUtils::has_invalid_symbols(const std::string& s) {
const auto begin = s.begin();
const auto end = s.end();
for (auto it = begin; it != end; ++it) {
if (!is_valid_operator_or_digit(*it) && *it != '(' && *it != ')') return true;
}
return false;
}
float CalculatorUtils::perform_operation_on_strings(const std::string &a, const std::string &b, const char &_operator) {
float afloat = std::atof(a.c_str());
float bfloat = std::atof(b.c_str());
switch (_operator) {
case '^':
return std::pow(afloat, bfloat);
case '*':
return afloat * bfloat;
case '/':
return afloat / bfloat;
case '+':
return afloat + bfloat;
case '-':
return afloat - bfloat;
case '%':
return fmod(std::stof(a), std::stof(b));
default:
return 0;
}
}