How to evaluate tokens in C?

180 views Asked by At

I'm trying to work on a program that takes a math expression from user input (2+2, 3*1, 4-2, 2+3*1, etc.) I've goten it to work with simple, one operation, but it doesn't work with multiple yet. I was suggested to tokenize and evaluate the string and while I managed to tokenize it, the manual I'm reading doesn't explain how to evaluate (I'm trying to learn on my own, no schoolwork for me) and google hasn't been super helpful.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
  char conta[255];
  int n1;
  int n2;
  int result;
  char op;

  printf("Introduza uma expressao numerica: ");
  gets(conta);
  sscanf(conta, "%d %c %d", &n1, &op, &n2);
  char* token = strtok(conta, "+-*/");
  while (token) {
    printf("token: %s\n", token);
    token = strtok(NULL, "+-*/");
  }
  if(op == '+'){
    printf("%d", result=n1+n2);
  }else if(op == '-'){
    printf("%d", result=n1-n2);
  }else if(op == '*'){
    printf("%d", result=n1*n2);
  }else if(op == '/'){
    printf("%d", result=n1/n2);
  }

}

This is what I have of the code so far. ANy help would be greatly apreciated, thank you.

1

There are 1 answers

0
Rogus On

You have to implement a parser for expressions, analyze the input and evaluate the order of equations so that e.g. 2+2*2 is 6 and not 8.

So let's examine the 2+2*2 example. Imagine that mathematical operations can be expressed in two ways, such that a*b is *(a,b) and c+d is +(c,d). So if you have the expression a+b*c it would be evaluated to +(a,*(b,c)). This is one way of making it happen.

You can also find a nice explanation on an LR parser wiki page (a type of bottom-up parser).

If the wiki page is not enough just look for top-down and bottom-up parsers.