I've done the basic calculator in which you enter the number, then the operator, and finally the last number. What I'm trying to create is a program that can produce the result 4 when a user provides the prompt 2+2. Using visual c++ I've realized that this code worked:
1 2 3 4 5 6 7 8 9 10
#include <iostream>
#include <conio.h>
int main()
{
int x = 2 + 2;
std::cout << x;
_getch();
return 0;
}
What I can't figure out is how to get that to work with user input. I know that the + character can't go into an int, but I'm not sure how exactly to append it to an int. Any help with the matter is greatly appreciated.
#include <iostream>
int main() {
int lhs;
int rhs;
char op;
std::cin >> lhs >> op >> rhs; // input the values
// change result based on the operator given
int result;
switch (op) {
case'+': result = lhs + rhs; break;
case'-': result = lhs - rhs; break;
// etc...
}
std::cout << result << std::endl;
return 0;
}
Thanks for the response NT3. Would you by any chance know how to make this calculator work with more complex questions like 2+3+2 or 25*2/4+1 or questions with more digits?
For example, if you wanted it to allow for order of operations, you'll need to parse the whole statement, split it into groups, and then evaluate each group in a bottom-up fashion to get the answer.
However, if you don't care, then its easy to modify my above code to do what you want:
#include <iostream>
#include <sstream>
#include <string>
int main() {
std::string eqn;
std::getline(std::cin, eqn);
std::istringstream in (eqn);
int result; // or double
int rhs; // or double
char op;
in >> result;
// while there are more values to get
while (in >> op >> rhs) {
switch (op) {
case'+': result += rhs; break;
case'-': result -= rhs; break;
// etc...
}
}
std::cout << result << std::endl;
return 0;
}