This program is individually checked operation, and can spot completion code.
Lexical analysis program ( Lexical Analyzer ) requirements:
- stream from a source program composed of character scan left to right
- identify the lexical meaning of the word ( Lexemes )
- Return word record (word class, the word itself)
- filtered spaces
- skip comments
- lexical errors found
Program Structure:
Input: character stream (input what way, what data structure stored)
deal with:
- Traverse (What traversal)
- lexical rules
Output: word stream (what output form)
- tuple
Word class:
1. Identifier (10)
2. unsigned (11)
3. Leave the word (the word one yard)
4. Operator (word one yard)
5. delimiter (word one yard)
Word symbols |
Species do not code |
Word symbols |
Species do not code |
begin |
1 |
: |
17 |
if |
2 |
:= |
18 |
then |
3 |
< |
20 |
while |
4 |
<= |
21 |
do |
5 |
<> |
22 |
end |
6 |
> |
23 |
l(l|d)* |
10 |
>= |
24 |
dd* |
11 |
= |
25 |
+ |
13 |
; |
26 |
- |
14 |
( |
27 |
* |
15 |
) |
28 |
/ |
16 |
# |
0 |
The source code
#include<stdio.h> #include"stdlib.h" #include <string.h> char* keyword[6]={"begin","if","then","while","do","end"}; int a[99]; char b[20]; int num=0; bool character(char c) { if(((c<='z')&&(c>='a'))||((c<='Z')&&(c>='A'))) { return true; } else return false ; } bool number(char c) { if((c<='9')&&(c>='0')) { return true; } else return false ; } int symbol(char *c) { if(strcmp("+",c)==0) return 13; if(strcmp("-",c)==0) return 14; if(strcmp("*",c)==0) return 15; if(strcmp("/",c)==0) return 16; if(strcmp(":",c)==0) return 17; if(strcmp(":=",c)==0) return 18; if(strcmp(">",c)==0) return 20; if(strcmp("<=",c)==0) return 21; if(strcmp("<>",c)==0) return 22; if(strcmp("<",c)==0) return 23; if(strcmp(">=",c)==0) return 24; if(strcmp("=",c)==0) return 25; if(strcmp(";",c)==0) return 26; if(strcmp("(",c)==0) return 27; if(strcmp(")",c)==0) return 28; return 404; } void empty(char *c) { memset(c, 0, 20); } int main () { FILE *fp; if((fp=fopen("C:\\Users\\15108\\Desktop\\test.c","r"))==NULL) { printf ( " file read error! " ); exit(0); } char c[20]; char n[20]; char f[20]; char temp[1]; empty(f); empty(c); empty(n); int x = 0 ; int y = 0 ; int z = 0 ; char ch; do{ ch=fgetc(fp); temp[0]=ch; int find=symbol(temp); if(find!=404) { f[z]=ch; from ++ ; }else if(z!=0){ int result=symbol(f); printf("<%d,%s>\n",result,f); with = 0 ; empty(f); } if((character(ch)) || ((x!=0) &&(number(ch)))) { c[x]=ch; x++; }else if(x!=0){ for(int i=0;i<6;i++) { if(strcmp(keyword[i],c)==0) { printf("<%d,%s>\n",i+1,c); x=0; empty(c); break; }else if(i==5) { printf("<%d,%s>\n",10,c); x=0; empty(c); break; } } } if((number(ch)) && (x==0)) { n [y] = ch; and ++ ; } else if((x==0) &&(y!=0) &&(!number(ch))){ printf("<%d,%s>\n",11,n); and = 0 ; empty(n); } }while(!(ch=='#')); }
Test text
if(x>5) x=10; and ++; then x=x/10; #
Screenshot results