1、#include#include#includeusing namespace std;#define keyword_num 13 #define delimiter_num 5 #define words_num 200 #define str_num 10 /变量定义char strstr_num; /str 用于存放接收的单词char wordswords_numstr_num;int i = 0 , n = -1 ,j=1, k; /i 作 str 的下标,n 作数组 words 行的下标int line_num=1; char c; char* keywordkeyword_num
2、 = “begin“,“call“,“const“,“do“,“end“,“if“,“odd“,“procedure“,“read“,“then“,“var“,“while“,“write“;/关键字 13 个按照顺序排列便于折半查找char delimiterdelimiter_num = ( , ) , ; , . , ,; /分界符 5 个FILE *fout; /存放分词结果的文件ifstream fin; string s; int main()printf(“输入文件名:“); cins; fin.open(s.c_str(); while(!fin.is_open() print
3、f(“文件不存在,请重新输入:“);fin.clear();cins; fin.open(s.c_str(); printf(“行 (类别 单词 )n“);/打开文件“分析结果.txt”,将分词结果写到该文件中fout = fopen(“分析结果.txt“,“w“); fprintf(fout,“行 (类别 单词 )n“);if(!fin.eof() c = fin.get(); while(1)/忽略回车、tab 键和空格,且当是回车时,行号加 1while(c = 10 | c =9 | c = )if(c = 10) + line_num;if(!fin.eof() c = fin.ge
4、t(); j=1;if(fin.eof() break;/关键字或标识符的接收,以字母或下划线开头if(c = a while(ab) /输出关键字,以行号,二元组(类型,单词)格式printf(“%-5d(关键字 , %-10s)n“,line_num, str);fprintf(fout, “%-5d(关键字 , %-10s)n“,line_num, str);else/输出标识符printf(“%-5d(标识符 , %-10s)n“,line_num, str);fprintf(fout, “%-5d(标识符 , %-10s)n“,line_num, str); for(;i=0;i-)
5、 stri=0; i=0; /常数接收,以数字或负号开头else if(0 = a flag=2;break;else j=0;break;/如果该单词含有两个小数点,报错for(k=0;k=0;i-) stri=0; i=0; else / 接收运算符或分界符/判断是否为分界符for(k=0;k=,单字符有case: str0=c;if(!fin.eof() c = fin.get(); if(c=)str1=c;strcpy(words+n,str);printf(“%-5d(运算符 , %-10s)n“, line_num,str);fprintf(fout, “%-5d(运算符 , %-10s)n“, line_num,str);str0=0;str1=0;break;elsej=0;strcpy(words+n,str);printf(“%-5d(运算符 , %-10s)n“, line_num,str);fprintf(fout, “%-5d(运算符 , %-10s)n“, line_num,str);str0=0;break;if(j)if(!fin.eof() c = fin.get(); fclose(fout);printf(“分词结束,共识别%d 个单词,保存在分析结果.txt 中n“,n+1); return(0);