Advanced C++ Calculator

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.
You'll need to input it into a char and then switch based on the character to determine what to do. For example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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;
}
2+2
4
Last edited on
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?
Yes, but it could get really complicated.

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:
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
#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;
}
10+5-8
7
Last edited on
Thank you very much NT3. The program works perfectly.
Topic archived. No new replies allowed.