The "nasty implementation" I mentioned is within the void calculator()
inside of calculator.cpp
. Everything goes well as long as user don't type in the erroneous syntax. But I think this isn't the good idea to implement it this way.
Can I do it the other way around with more reasonable implementation without losing the functionality of being able to calculate infinitely(not really,I know).
main.cpp:
#include <iostream>
#include "calculator.h"
int main()
{
calculator();
return 0;
}
calculator.cpp:
#include <iostream>
#include <cassert>
#include "calculator.h"
int getIntInput()
{
int x{};
std::cin >> x;
assert("Syntax Error!!" && !std::cin.fail());
return x;
}
char getOperatorInput()
{
char x{};
std::cin >> x;
bool b{x == '+' || x == '-' || x == '*' || x == '/' || x == '^'};
assert("Syntax Error!!" && b);
return x;
}
int calculate(int x)
{
char op{getOperatorInput()};
int tmp{getIntInput()};
if(op == '+')
{
return x + tmp;
}
else if(op == '-')
{
return x - tmp;
}
else if(op == '*')
{
return x * tmp;
}
else if(op == '/')
{
return x / tmp;
}
return 0;
}
void calculator()
{
std::cout << "Enter your expression : ";
int64_t result{};
int loopCount{0};
do{
if(loopCount == 0)
result = getIntInput();
result = calculate(result);
loopCount++;
}
while(std::cin.peek() != '\n');
std::cout << "Your result is : " << result << '\n';
}
calculator.h:
#ifndef CALCULATOR_H
#define CALCULATOR_H
int getIntInput();
char getOperatorInput();
void calculator();
#endif // CALCULATOR_H
```