C语言实现简单算术表达式解析器
#include <stdio.h> #include <ctype.h>
char lookahead;
void error() { printf("FOUND ERROR"); exit(1); }
void match(char expected) { if (lookahead == expected) { lookahead = getchar(); } else { error(); } }
void E(); void T(); void F();
void E() { T(); while (lookahead == '+') { match('+'); T(); } }
void T() { F(); while (lookahead == '') { match(''); F(); } }
void F() { if (isdigit(lookahead)) { match(lookahead); } else if (isalpha(lookahead)) { match(lookahead); } else if (lookahead == '(') { match('('); E(); match(')'); } else { error(); } }
int main() { printf("Enter an arithmetic expression # : "); lookahead = getchar(); E(); if (lookahead == '#' && getchar() == '\n') { printf("SUCCESS"); } else { error(); } return 0; }
// Example input: # i1*( i2+i3)# // Output: SUCCESS
原文地址: https://www.cveoy.top/t/topic/nGg4 著作权归作者所有。请勿转载和采集!