詞法分析器 C語言

2021-08-29 15:55:11 字數 3686 閱讀 6370

#include

#include

#include

#include

#include

int i, row =

0, line =0;

char test[

1000];

//test檔案中的字元

int number[

100]

;//常數表

char mark[

100][5

];//識別符號表

//詞法分析

int wordanalysis()

; int n =0;

word[n++

]= test[i++];

while

((test[i]

>=

'a'&&test[i]

<=

'z')

||(test[i]

>=

'0'&& test[i]

<=

'9')

||(test[i]

>=

'a'&&test[i]

<=

'z')

) word[n]

='\0'

; i--

;//判斷該識別符號是否為保留字

for(n =

0; n <

100; n++)}

//判斷該識別符號是否在識別符號表中

int m =0;

if(line !=0)

}}//將該識別符號儲存到識別符號表中

strcpy

(mark[line]

, word)

;printf

(">> %s\t(25, %d) 識別符號\n"

, word, line +1)

; line++

;return3;

}//數字

else

if(test[i]

>=

'0'&& test[i]

<=

'9')

x[n]

='\0'

; i--

; int num =

atoi

(x);

//將字串轉換成int型

//判斷該常數是否存在於常數表中

if(row !=0)

}}//將該常數儲存到識別符號表中

number[row]

=num;

int line = row;

printf

(">> %d\t(26,%d)\n"

, num, line +1)

; row++

;return3;

}//各種符號

else

switch

(test[i]

)else

if(test[i]

=='>'

)else

case

'>'

: i++;if

(test[i]

=='='

)else

case

'+':

printf

(">> +\t(33,-)\n");

return3;

case

'-':

printf

(">> -\t(34,-)\n");

return3;

case

'*':

printf

(">> *\t(35,-)\n");

return3;

case

'/':

i++;if

(test[i]

!='/'

)else

printf

(">> //\t(37,-)\n");

return3;

}case

':':

printf

(">> :\t(38,-)\n");

return3;

case

';':

printf

(">> ;\t(39,-)\n");

return3;

case

'(':

printf

(">> (\t(40,-)\n");

return3;

case

')':

printf

(">> )\t(41,-)\n");

return3;

case'':

printf

(">> }\t(43,-)\n");

return3;

case

'[':

printf

(">> [\t(44,-)\n");

return3;

case

']':

printf

(">> ]\t(45,-)\n");

return3;

case

'|':

printf

(">> |\t(46,-)\n");

return3;

case

'"':

printf

(">> \"\t(47,-)\n");

return3;

case

',':

printf

(">> ,\t(48,-)\n");

return3;

case

'\''

:printf

(">> '\t(49,-)\n");

return3;

//單引號

case

'&':

i++;if

(test[i]

!='&'

)else

case

'\\'

:printf

(">> \\\t(52,-)\n");

return3;

}}int main()

while(!

feof

(fp)

) test[c]

='#';do

}while

(m !=0)

;return0;

}

test.txt檔案中的內容

int i, row =

0, line =0;

char test[

1000];

//test檔案中的字元

int number[

100]

;//常數表

char mark[

100][5

];//識別符號表

//詞法分析

int wordanalysis()

{//識別符號和保留字if(

(test[i]

>=

'a'&&test[i]

<=

'z')

||(test[i]

>=

'a'&&test[i]

<=

'z')){

char word[10]

;//保留字表

詞法分析器(分析C語言)

用c或c 語言編寫乙個簡單的詞法分析程式,掃瞄c語言小子集的源程式,根據給定的詞法規則,識別單詞,填寫相應的表。如果產生詞法錯誤,則顯示錯誤資訊 位置,並試圖從錯誤中恢復。簡單的恢復方法是忽略該字元 或單詞 重新開始掃瞄。相關詞法規則 識別符號 字母 識別符號 識別符號 字母 識別符號 識別符號 數...

c語言詞法分析器

include include include void main void int reserver char void main void if output fopen output.txt wt null fprintf output,4s t 8s t 16s t 4s n 位置 符號型別...

C語言詞法分析器

include include include include define len 180 int syn,p,m,n char token 10 ch char keyword 32 struct wordline 定義結構體 struct wordline creat struct wordl...