Ein Parser für einfache Ausdrücke in C
#include <stdio.h>
#include <math.h>
#include <string.h>
double xpow( double const x, double const y ){ return pow( x, y ); }
double xmul( double const x, double const y ){ return x * y; }
double xdiv( double const x, double const y ){ return x / y; }
double xadd( double const x, double const y ){ return x + y; }
double xsub( double const x, double const y ){ return x - y; }
typedef double( *operator )( double, double );
struct ex { char name; operator op; int left; }ex[] =
{ { 0, 0, 0 }, { '^', xpow, 0 },{ '*', xmul, 1 },{ '/', xdiv, 1 },
{ '+', xadd, 1 },{ '-', xsub, 1 }};
struct ex lookup( char const name )
{ for( size_t i = 0; i < sizeof ex/sizeof 0[ ex ]; ++i )
if( ex[ i ].name == name )return ex[ i ]; return ex[ 0 ]; }
char const * g = 0; char get(){ return *g++; }
char peek(){ return *g; }
char check( char const * const op )
{ return strchr( op, peek() ) ?get(): 0; }
double numeral(){ return get() - '0'; }
double prefix(){ int sign = 1;
while( '-' == peek() ){ get(); sign *= -1; }
return sign * numeral(); }
double parse( char const * const op, double( *next ) () )
{ double result =( *next )();
for( char sym; sym = check( op ); )result = lookup( sym ).op
( result, lookup( sym ).left?( next )(): parse( op, next ));
return result; }
double power(){ return parse( "^", prefix ); }
double product(){ return parse( "/*", power ); }
double sum(){ return parse( "+-", product ); }
double start(){ return sum(); }
void test( char const * s ){ g = s; printf( "%g\n", start() ); }
int main( void ){ test( "2^2^3/2/2" ); test( "2+2*2^2^-3" ); }
64
4.18102