[ create a new paste ] login | about

Link: http://codepad.org/z7DsoYHG    [ raw code | output | fork ]

C, pasted on Oct 6:
#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>

int nextc;
#define peek(c)  (nextc == c)
int match(int c) {
  if (peek(c)) {
    while((nextc = getchar()) == '=' || nextc == '\r')
      ;
    return nextc;
  } else
    return 0;
}

jmp_buf env;
void error(viod)
{
  printf("syntax error.\n");
  while (!peek('\n'))
    nextc = getchar();
  longjmp(env, 1);
}

int exp0(void);
int exp1(int);
int term0(void);
int term1(int);
int factor(void);

int main()
{
  int n;

  if (scanf("%d", &n) != 1)
    return -1;
  while ((nextc = getchar()) == '\r')
    ;
  while (n-- > 0) {
    setjmp(env);
    nextc = getchar();
    printf("%d\n", exp0());
  }
  return 0;
}

int exp0(void)
{                                   /* E -> TA */
  double v = term0();
  return exp1(v); 
}

int exp1(int v)
{
  if(match('+')) {                  /* A -> +TA */
    v += term0(); return exp1(v);
  } else if(match('-')) {           /* A -> -TA */
    v -= term0(); return exp1(v);
  } else 
    return v;                       /* A -> epsilon */
}

int term0(void) {                /* T -> FB */
  int v = factor();
  return term1(v);
}

int term1(int v) {
  if(match('*')) {                  /* B -> *FB */
    v *= factor(); return term1(v);
  } else if(match('/')) {           /* B -> /FB */
    v /= factor(); return term1(v);
  }  else                           /* B -> epsilon */
    return v;
}

#define N 1024
int factor(void) {               /* F -> 0...9 */

  static char buf[N];
  static char numtab[] = "0123456789", *p;
  int flag, i;

  i = 0;
  while (1) {
    flag = 0;
    for (p = numtab; *p != '\0'; p++) {
      if (match(*p)) {
        flag = 1;
        break;
      }
    }
    if (flag == 1) {
      buf[i++] = (char)*p;
      continue;
    } else {
      if (i == 0)
        break;
      else
        buf[i] = '\0';
      return atoi(buf);
    }
  }
  if(match('(')) {             /* F -> (E) */
    int v = exp0();
    if(match(')')) return v;
    else error();
  } else {
    error();
  }
}
/* end */


Output:
1
Exited: ExitFailure 255


Create a new paste based on this one


Comments: