Created
October 22, 2008 01:24
-
-
Save hakobe/18502 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <ctype.h> | |
#define MAX_INPUT_SIZE 1024 | |
#define TK_NOTHING 0 | |
#define TK_NUM 1 | |
#define TK_OP_PLUS 10 | |
#define TK_OP_MINUS 11 | |
#define TK_OP_DIV 12 | |
#define TK_OP_MULTI 13 | |
int POS = 0; | |
char *CONTENT = NULL; | |
char TOKEN[MAX_INPUT_SIZE]; | |
void init(char *buf) { | |
CONTENT = buf; | |
POS = 0; | |
} | |
int next_token() { | |
char c; | |
int sub_pos; | |
if (CONTENT == NULL) return TK_NOTHING; | |
while (CONTENT[POS] != '¥0' && POS < MAX_INPUT_SIZE) { | |
c = CONTENT[POS]; | |
if ( isdigit(c) ) { | |
sub_pos = 0; | |
while (isdigit(c) && CONTENT[POS] != '¥0' && POS < MAX_INPUT_SIZE) { | |
TOKEN[sub_pos++] = c; | |
c = CONTENT[++POS]; | |
} | |
TOKEN[sub_pos] = '¥0'; | |
return TK_NUM; | |
} | |
else if (c == '+') { | |
POS++; | |
return TK_OP_PLUS; | |
} | |
else if (c == '-') { | |
POS++; | |
return TK_OP_MINUS; | |
} | |
else if (c == '/') { | |
POS++; | |
return TK_OP_DIV; | |
} | |
else if (c == '*') { | |
POS++; | |
return TK_OP_MULTI; | |
} | |
else { | |
POS++; | |
// do nothing | |
} | |
} | |
return TK_NOTHING; | |
} | |
char *get_token() { | |
return TOKEN; | |
} | |
int main() { | |
int x, y, result; | |
int op; | |
char buf[MAX_INPUT_SIZE]; | |
fgets(buf, MAX_INPUT_SIZE, stdin); | |
if (buf == NULL) { | |
fprintf(stderr, "input error¥n"); | |
exit(EXIT_FAILURE); | |
} | |
init(buf); | |
if (next_token() != TK_NUM) { | |
fprintf(stderr, "parse error¥n"); | |
exit(EXIT_FAILURE); | |
} | |
x = atoi(get_token()); | |
op = next_token(); | |
if ( !( | |
op == TK_OP_PLUS || | |
op == TK_OP_MINUS || | |
op == TK_OP_DIV || | |
op == TK_OP_MULTI | |
) | |
) { | |
fprintf(stderr, "parse error¥n"); | |
exit(EXIT_FAILURE); | |
} | |
if (next_token() != TK_NUM) { | |
fprintf(stderr, "parse error¥n"); | |
exit(EXIT_FAILURE); | |
} | |
y = atoi(get_token()); | |
switch (op) { | |
case TK_OP_PLUS: | |
result = x + y; | |
break; | |
case TK_OP_MINUS: | |
result = x - y; | |
break; | |
case TK_OP_DIV: | |
if (y == 0) { | |
fprintf(stderr, "0 division error¥n"); | |
exit(EXIT_FAILURE); | |
} | |
result = x / y; | |
break; | |
case TK_OP_MULTI: | |
result = x * y; | |
break; | |
} | |
printf("result: %d¥n", result); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment