Search code examples
cstringtype-conversionintegerexpression

Is there any C function that can evalute a string expression defined in the standard library?


I am looking for a function that can evaluate a string expression into an integer, like f.e.:

10/2+4*3-(12+5); //Equals 0

into an object of type int with the value of 0.

A function for complex operation would be preferable even though that's not the need of the hour:

2^(1/2)-99

Is there any such definition defined in the standard C library (C89, C90, if it's compiled)?

Is there any non-standard library which has such an function?

The more the characters the expression supports the better it is.

But even basic operation like +,-,*,/,() would do.


Solution

  • Is there any such definition defined in the standard C library (C89, C90, if it's compiled)?

    No, not even in the more recent standard libraries of C11 or C18.

    Is there any non-standard library which has such an function?

    I couldn´t found one either. You have to write your own function to accomplish that.

    Maybe scan the string and store every value in it to a separate string at the first step.

    As I already suggested in the comments, strtol is used to convert an integer value like 11 in a string to a value of type int. You might need to take use of that. In the libraries there is also a function of atoi to convert an integer value inside a string to an int but this function is more susceptible for errors and should not be used.

    The arithmetic operators shall be stored in separate strings also, but later evaluated by a self-made routine.

    But good examples and recommendations can be found here, where a user have been asked a similar (if not the same) question:

    C: convert a mathematical expression string into an int with the result