std::string invalid_string(std::string example)
{
if (example.find("", 0) != -1)
std::cout << "Error string is empty" << std::endl;
for (size_t i = 0; i < example.size(); ++i) {
if (example[i] == ' ') {
example.erase(i, 1);
--i;
}
}
return example;
}
void counter(std::vector<float>& num, std::vector<char>& arithmetic_sign, char oper)
{
while (std::find(arithmetic_sign.begin(), arithmetic_sign.end(), oper) !=
arithmetic_sign.end()) {
size_t index = std::find(arithmetic_sign.begin(), arithmetic_sign.end(), oper) -
arithmetic_sign.begin();
switch (oper) {
case '+':
num[index] += num[index + 1];
break;
case '-':
num[index] -= num[index + 1];
break;
case '*':
num[index] *= num[index + 1];
break;
case '/':
num[index] /= num[index + 1];
break;
}
num.erase(num.begin() + (index + 1));
arithmetic_sign.erase(arithmetic_sign.begin() + index);
}
}
int logic(std::string example, float& result)
{
invalid_string(example);
if (example.find("(", 0) != -1) {
int open = example.find("(", 0);
int close = example.rfind(")", example.size());
char tmp[10] = "";
_itoa(logic(example.substr(open + 1, close - (open + 1)), result), tmp, 10);
example.erase(example.begin() + open, example.begin() + close + 1);
example.insert(open, tmp);
}
std::vector<float> num;
std::vector<char> arithmetic_sign;
std::regex num_regex("[0-9]+");
for (std::sregex_token_iterator it(begin(example), end(example), num_regex), last; it != last;
++it) {
num.push_back(std::stoi(it->str()));
}
std::regex arithmetic_regex("[\(\)\*\+\/-]");
for (std::sregex_token_iterator it(begin(example), end(example), arithmetic_regex), last;
it != last; ++it) {
arithmetic_sign.push_back(it->str()[0]);
}
while (std::find(arithmetic_sign.begin(), arithmetic_sign.end(), '(') !=
arithmetic_sign.end()) {
size_t index = std::find(arithmetic_sign.begin(), arithmetic_sign.end(), '(') -
arithmetic_sign.begin();
size_t rindex = std::find(arithmetic_sign.begin(), arithmetic_sign.end(), ')') -
arithmetic_sign.begin();
std::string str;
for (size_t i = index; i != rindex; ++i) {
char tmp[5] = "";
str.push_back(*(_itoa(num[index], tmp, 10)));
str.push_back(arithmetic_sign[index + 1]);
}
}
counter(num, arithmetic_sign, '*');
counter(num, arithmetic_sign, '/');
counter(num, arithmetic_sign, '-');
counter(num, arithmetic_sign, '+');
result = num.at(0);
return result;
}
int main()
{
float result;
std::string example = "";
std::cout << "Enter your mathimatical example: ";
std::getline(std::cin, example);
logic(example, result);
std::cout << "Result = " << result << std::endl;
return 0;
}