Skip to content

Instantly share code, notes, and snippets.

@antonijn
Last active August 29, 2015 14:05
Show Gist options
  • Save antonijn/d491049bcfca51c3f7dd to your computer and use it in GitHub Desktop.
Save antonijn/d491049bcfca51c3f7dd to your computer and use it in GitHub Desktop.
Simple polish notation solver
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
double expr(FILE *f)
{
double acc = 0.0;
int nxt = fgetc(f);
if (isspace(nxt))
return expr(f);
switch (nxt) {
case '+':
return expr(f) + expr(f);
case '-':
return expr(f) - expr(f);
case '*':
return expr(f) * expr(f);
case '/':
return expr(f) / expr(f);
}
ungetc(nxt, f);
if (fscanf(f, "%lf", &acc))
return acc;
fputs("syntax error\n", stderr);
exit(1);
}
int main(void)
{
printf("%f\n", expr(stdin));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment