📄 词法分析.cpp
字号:
#include<iostream>
#include<fstream>
#include<stdlib.h>
#include<string>
using namespace std;
#define MAX 100
struct Word{
char spelling[50];
};
Word word;
/*struct ID{
char *id[MAX];
int point1;
};
ID SIGN;
struct NUMBER{
char *num[MAX];
int point2;
};
NUMBER NUM;*/
void main(){
char c;
//char *s=new char;
cout<<"03级计算机一班王强"<<endl<<"学号:200345003086"<<endl;
// cout<<"输入要打开文件的路径:";
// cin>>s;
char *ID[MAX];ID[0]=NULL;
char *NUM[MAX];NUM[0]=NULL;
int pos=0,point1=0,point2=0,i,j;
char *name[36]={" ","and","array","begin","bool","call","case",
"char","constant","dim","do","else","end","false","for",
"if","input","integer","not","of","or","output","procedure",
"program","read","real","repeat","set","stop","then",
"to","true","until","var","while","write"};
fstream f("TEST1",ios::in);
f.seekp(-1,ios::end);
long posEnd=f.tellp();
f.seekp(0,ios::beg);
f.get(c);
while(f.tellp()!=posEnd){
if(c==' '||c=='\n')f.get(c);
else{
switch(c){
case '(':cout<<"(39 , - )"<<" ";break;
case ')':cout<<"(40 , - )"<<" ";break;
case '*':
f.get(c);
if(c=='/')cout<<"(42 , - )"<<" ";
else {cout<<"(41 , - )"<<" ";f.seekp(-1,ios::cur);}
break;
case '+':cout<<"(43 , - )"<<" ";break;
case ',':cout<<"(44 , - )"<<" ";break;
case '-':cout<<"(45 , - )"<<" ";break;
case '.':
f.get(c);
if(c=='.')cout<<"(47 , - )"<<" ";
else {cout<<"(46 , - )"<<" ";f.seekp(-1,ios::cur);}
break;
case '/':
f.get(c);
if(c=='*')cout<<"(49 , - )"<<" ";
else {cout<<"(48 , - )"<<" ";f.seekp(-1,ios::cur);}
break;
case ':':
f.get(c);
if(c=='=')cout<<"(51 , - )"<<" ";
else {cout<<"(50 , - )"<<" ";f.seekp(-1,ios::cur);}
break;
case ';':cout<<"(52 , - )"<<" ";break;
case '<':
f.get(c);
if(c=='=')cout<<"(54 , - )"<<" ";
else if(c=='>')cout<<"(55 , - )"<<" ";
else{cout<<"(53 , - )"<<" ";f.seekp(-1,ios::cur);}
break;
case '=':cout<<"(56 , - )"<<" ";break;
case '>':
f.get(c);
if(c=='=')cout<<"(58 , - )"<<" ";
else {cout<<"(57 , - )"<<" ";f.seekp(-1,ios::cur);}
break;
case '[':cout<<"(59 , - )"<<" ";break;
case ']':cout<<"(60 , - )"<<" ";break;
}
if(c>='a'&&c<='z'||c>='A'&&c<='Z'){
word.spelling[pos]=c;
pos++;
f.get(c);
if(c<='0'||c>='9'&&c<='A'||c>='z'){
for(i=1;i<=37;i++){
if(strcmp(word.spelling,name[i])==0){
cout<<"("<<i<<" , - )"<<" ";break;
}
}
if(i>37){
for(j=0;j<=point1;j++){
if(strcmp(word.spelling,ID[j])==0)
cout<<"("<<36<<" , "<<j+1<<" )"<<" ";
}
if(j>point1){
strcpy(ID[point1],word.spelling);
point1++;
}
}
for(i=0;i<=pos;i++)word.spelling[i]=NULL;
pos=0;
}
}
else if(c>='0'&&c<='9'){
word.spelling[pos]=c;
pos++;
f.get(c);
if(c<='0'||c>='9'){
for(j=0;j<=point2;j++){
if(strcmp(word.spelling,NUM[j])==0)
cout<<"("<<37<<" , "<<j+1<<" )"<<" ";
}
if(j>point2){
strcpy(NUM[point2],word.spelling);
point2++;
}
for(i=0;i<=pos;i++)word.spelling[i]=NULL;
pos=0;
}
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -