1

Sorry for my lack of English skills.

I want to do an arithmetic operation specified in a string, e.g. "1 + 3 * 11 - 7 / 18".

Multiplication and division have higher priority than addition and subtraction. In the case of operations with the same priority, operations are performed in order from left to right.

I've written code that computes the addition. But I can not get to the next step.

#include <iostream>
#include <string>

using namespace std;

int main() {
  string s;
  cout << "Enter an arithmetic operation EX) 1 + 3 * 11 + 7 / 18 " << endl;
  getline(cin, s, '\n'); 
  int sum = 0;
  int search = 0; 

  while(true) {
      int plus = s.find('+', search);
      if(plus == -1) { 
          string aos = s.substr(search);
          if(aos == "") break; 
          cout << aos << endl;
          sum += stoi(aos); 
          break;
      }

      int count = plus - search; 
      string aos = s.substr(search, count);  
      cout << aos << endl;
      sum += stoi(aos);
      search = plus+1; 

   }
   cout << "Result is " << sum;
}
jotik
  • 17,044
  • 13
  • 58
  • 123

1 Answers1

1

There is no built-in way to parse and evaluate a string. You'll need to write your own code to do this.

Typically, expression evaluation proceeds in two steps:

  1. Scanning. Rather than working with a single string, break the input apart into individual units called tokens. For example, the string 5 * 3 + 2 might turn into the sequence ["5", "*", "3", "+", "2"]. By doing this step in advance, you make it a lot easier to work with the quantities later on, since there's no need to do a ton of complex string processing.

  2. Evaluation. Given the sequence of tokens, determine what the expression evaluates to.

The approach you're taking - finding an operator and evaluating it - can be made to work. You'll want to search for the highest-priority operator first to evaluate. For example, in the string 5 * 3 + 2, you'd need to evaluate 5 * 3 before 3 + 2.

However, there are other faster and cleaner ways to do this. Dijkstra's shunting-yard algorithm uses two stacks to evaluate expressions and is relatively straightforward to code up. I'd recommend starting there - every time I've needed to make an expression evaluator by hand, I've turned to this particular approach.

There are other heavyweight options. You could look online for an expression parsing library, or you could use a tools like flex and bison to automatically generate a parser. I suspect that's overkill for what you need, though.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065