How to get and evaluate expressions from a string in C

How to get and evaluate expressions from a string in C

char *str = "2*8-5+6";

      

This should give a score of 17 after being evaluated.

+3


source to share


3 answers


Try it yourself. you can use the stack data structure to evaluate this string here, this is the implementation reference (its in C ++) stack data structure for string computation



+3


source


You have to do it yourself, C provides no way to do this. C is a very low level language. The easiest way to do this is to find a library that does it, or if that doesn't exist, use lex + yacc to create your own interpreter.

A quick google suggests the following:



+2


source


You should try TinyExpr . This is one C source code (no dependencies) that you can add to your project.

Using this solution to solve your problem is simple:

#include <stdio.h>    
#include "tinyexpr.h"

int main()
{
    double result = te_interp("2*8-5+6", 0);
    printf("Result: %f\n", result);
    return 0;
}

      

This will print: Result: 17

+1


source







All Articles