C four arithmetic expression parser

Download example: http://www.wisdomdd.cn/Wisdom/resource/articleDetail.htm?resourceId=1074

The program mainly includes: basic structure definition, lexical analysis, syntax analysis, arithmetic operation

Basic structure definition: enumeration (operand types, operator types, token types, finite state automata);

Structure (operands, operators, tokens, token chains).

Lexical analysis: Decompose a string into valid tokens (valid operands and operators), and generate a linked list of tokens.

Syntax analysis: Analyze the validity of parentheses, the validity of the arrangement of operands and operators, and the matching relationship between operators and operand types.

Arithmetic operation: Use the postfix expression operation rules to evaluate according to the postfix expression linked list. First convert the infix expressions we use every day into postfix expressions. For example: 6*(5-3) converts to 6 5 3 - *, 6-2+5*2 converts to 6 2 - 5 2 * +

C four arithmetic expression parser

Here is a description of the conversion of postfix expressions, each operator has an operation priority (oper_PRI), but when the expression contains parentheses, the operation priority of the operators in the parentheses will change. So a bracket depth priority (deep_PRI) is added. Using the two-level approach is simpler and easier to read than using the stack.

operator oper_PRI
+ 7
- 7
* 9

When converting, the operator has two priorities, expressed as: operator (deep_PRI, oper_PRI)

Input each token of the expression 5+(8-2*3)*4 in turn and finally output 5 8 2 3 * - 4 * +.

enter temporary space

When entering an operator, put a temporary empty

time, trigger the action at the same time.

operator(deep_PRI,oper_PRI)

Initial deep_PRI=0

action

When '(' is entered, deep_PRI++

When entering ')', deep_PRI--

When entering an operator, the previous operator is compared to it

Priority, if true, output the previous operator.

Comparison rules:

deep_PRI > deep_PRI ||

(deep_PRI == deep_PRI &&

oper_PRI >= oper_PRI)

output

operand directly

output

5     5
+ +(0,7)    
( +(0,7) deep_PRI++  
8 +(0,7)   8
- +(0,7)

-(1,7)

+(0,7) compared to -(1,7)

0>1||(0==1&&7>=7) is false, no output

 
2 +(0,7)

-(1,7)

  2
* +(0,7)

-(1,7)

*(1,9)

-(1,7) compared with *(1,9)

1>1||(1==1&&7>=9) is false, no output

 
3 +(0,7)

-(1,7)

*(1,9)

  3
) +(0,7)

-(1,7)

*(1,9)

deep_PRI--  
* +(0,7)

-(1,7)

*(1,9)

*(0,9)

*(1,9) compared with *(0,9)

1>0||(1==0&&9>=9) is true output *(1,9)

*
  +(0,7)

-(1,7)

*(0,9)

-(1,7) compared with *(0,9)

1>0||(1==0&&7>=9) is true output -(1,7)

-
  +(0,7)

*(0,9)

+(0,7) compared with *(0,9)

0>0||(0==0&&7>=9) is false, no output

 
4 +(0,7)

*(0,9)

  4
  +(0,7)

*(0,9)

No operator: output temporary space values ​​in reverse order *
  +(0,7)   +

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325032710&siteId=291194637