⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cifafenxi.cpp

📁 词法分析程序 能够正确进行词法分析
💻 CPP
字号:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string Kwords[]={"int","char","cin","cout","end","ood","if","then","call","while","do","read","write","for"};

bool isKeyWord(string word){
    bool   flag=false;
    for (int i=0;i<14;i++)
     if (word==Kwords[i]) flag=true;
    return flag;
  }

bool isDigit(char ch){
    if(ch>=0x30 && ch<=0x39) return true;else return false;
  }
bool isLetter(char ch){
    if((ch>=0x61 && ch<=0x7a)||(ch>=0x41&&ch<=0x5a)) return true;else return false;
  }

int Typeof(char w){
    if(isDigit(w)) return 0;
    else if(isLetter(w)) return 1;
    else return 2;
  }

class FileReader{
   private:
       ifstream inpfile;
   public:
       FileReader(){
           inpfile.open("in.txt");
       }
       ~FileReader(){
           inpfile.close();
       }
       char peekNextChar(){
           if (!inpfile.eof())
		   {
           char p=inpfile.peek();
           return p;
		   }
           else return 0;
        }
       char getNextChar(){
           if (!inpfile.eof())
		   {
           char p=inpfile.get();
           return p;
		   }
           else return 0;
        }
        bool eof(){
           return inpfile.eof();
         }
};

char getch(FileReader* inp){
    return inp->getNextChar();
  }
char peekch(FileReader* inp){
    return inp->peekNextChar();
  }
int main()
{
    FileReader f;
    char buff[10];
    int pos=0;
     while(!f.eof())
	 {
       for (int i=0;i<10;i++)buff[i]=0;
       pos=0;
       buff[pos++]=getch(&f);
       while ((Typeof(peekch(&f))==Typeof(buff[0])||Typeof(peekch(&f))==1&&Typeof(buff[0])==0||Typeof(peekch(&f))==0&&Typeof(buff[0])==1)&&peekch(&f)!=NULL)buff[pos++]=getch(&f);

       switch(Typeof(buff[0]))
	   {
           case 0:cout<<buff<<"是数字"<<endl;break;
           case 1:if (isKeyWord(buff))cout<<buff<<"是关键字"<<endl;
			       else cout<<buff<<"是标识符"<<endl;
                   break;
        }
    }
	 return 0;

 }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -