-1

How do you calculate, given that the input is as follows?

All the questions are in the format of You also took note that all the numbers were positive integers and there were only 3 types of operators: +, - and *.

Sample Input 1

5 - 3

Sample Output 1

2

Sample Input 2

7 * 7

Sample Output 2

49

Sample Input 3

13 + 4

Sample Output 3

17

Lukey
  • 13
  • 3
  • 1
    Please, start with [Tour](https://stackoverflow.com/tour) and [How to ask](https://stackoverflow.com/help/how-to-ask). Your question is unclear, bad formatted, and lacks to show your own effort. Wait a few seconds, and it will start to collect down-votes... – Scheff's Cat Mar 16 '19 at 09:53
  • Better but the 2nd paragraph is still somehow confused... – Scheff's Cat Mar 16 '19 at 09:57
  • 1
    To solve "arbitrary" expressions you get from input, you need a [parser](https://en.wikipedia.org/wiki/Parsing)/interpreter. In your case, a very simple one. This could transform your input into -> [RPN (reverse polish notation)](https://en.wikipedia.org/wiki/Reverse_Polish_notation) which is easy to solve using stacks. – Scheff's Cat Mar 16 '19 at 10:00
  • 1
    A sample for a simple parser [SO: How to rearrange a string equation?](https://stackoverflow.com/a/50021308/7478597) and another little bit less simple [SO: Tiny Calculator](https://stackoverflow.com/a/46965151/7478597). – Scheff's Cat Mar 16 '19 at 10:04
  • I tried some different google researchs. The most promising was IMHO [google "simple expression parser in C++"](https://www.google.com/search?q=simple+expression+parser+in+C%2B%2B). – Scheff's Cat Mar 16 '19 at 10:11

2 Answers2

0

You are tasked to write a calculator in https://en.wikipedia.org/wiki/Reverse_Polish_notation . There are many tutorials on the web on how to do this.

D.R.
  • 17,368
  • 19
  • 70
  • 158
  • So, it was not that unclear to you than to me. ;-) I read the question again but I still didn't get how you could recognize RPN in it. (That doesn't mean that I think you're wrong.) ;-) – Scheff's Cat Mar 16 '19 at 09:57
  • 1
    From the now differently formatted input & output I'm not so sure anymore about my answer...let's wait for an even better formatted one...it is still very confusing. – D.R. Mar 16 '19 at 09:59
0

Well, since you have no requirements in regards to implementation, a simple switch statement would do. Here's a simple example implementation. If you are new to C++, note down std::cerr.

#include <iostream>
#include <cstdlib>

int main()
{
  int a, b;
  char op;
  std::cin >> a >> op >> b;
  switch (op)
  {
    case '+':
    {
      std::cout << a + b << std::endl;
      break;
    }
    case '-':
    {
      std::cout << a - b << std::endl;
      break;
    }
    case '*':
    {
      std::cout << a * b << std::endl;
      break;
    }
    default:
    {
      std::cerr << "Invalid operator" << std::endl;
      return EXIT_FAILURE;
    }
  }
  return EXIT_SUCCESS;
}
Ayxan Haqverdili
  • 17,764
  • 5
  • 27
  • 57