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

📄 sy2.cpp

📁 编制一个读单词过程
💻 CPP
字号:
#include <fstream>
#include <iostream>
#include <string>
char ch ;
void main()
{
 void scanner(ifstream&,ofstream&);
 ifstream fin("input.txt",ios::in);
 if (fin.fail()) cout << "找不到文件" << endl;
 ofstream fout("output.txt");
 scanner(fin,fout);
 fin.close();
 fout.close();
}

int judge(char *string) // 判断是否为关键字
{
 char *keywords[9]={"int","char","void","if","return","else","for","include","while"};//关键字表,按相应类型号排序
 for(int i = 0;i <= 8;i++) //遍历keywords数组
 {

  if (!strcmp(string,*(keywords+i)))
  {
  return i+1;
  }
 }
 return 0;
}

void scanner(ifstream &fin,ofstream &fout)
{
 char temp[100];
 int j=0,i=0;
 int value_judge;
 while (fin.get(ch))
 {
  if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
  {
   while((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||(ch>='0'&&ch<='9'))
   {
       temp[j]=ch;
       j++;
       fin.get(ch);
   }
   temp[j] = '\0'; //标志字符串结束
   j = 0;
   if (value_judge = judge(temp))
   {
    fout<<temp<<" "<<"(第"<<value_judge<<"保留字)"<<endl;
   }
   else fout<<temp<<" "<<"(标识符)"<<endl;

  }
  if(ch>='0'&&ch<='9')
  {
   while(ch>='0'&&ch<='9'||ch=='.')
   {
       if(ch=='.')i++;
       temp[j]=ch;
       j++;
       fin.get(ch);
   }
   temp[j] = '\0';
   j = 0;
   if(i>1)
   {
    fout << temp << " " << "(error)" << endl;
    i=0;
   }
   else fout << temp << " " << "(数字)" << endl;
   fin.seekg(-1,ios::cur);
  }
     else if (ch == '=') fout << "=" << " " << "(运算符)" << endl;
     else if (ch == '+') fout << "+" << " " << "(运算符)" << endl;
     else if (ch == '-') fout << "-" << " " << "(运算符)" << endl;
     else if (ch == '*') fout << "*" << " " << "(运算符)" << endl;
     else if (ch == '<')
      {
       fin.get(ch);
       if (ch == '=') fout << "<=" << " " << "(运算符)" << endl;
       else if (ch == '>') fout << "<>" << " " << "(运算符)" << endl;
       else
       {
        fout << "<" << " " << "(运算符)" << endl;
        fin.seekg(-9,ios::cur);
       }
      }
     else if (ch == '>')
      {
       fin.get(ch);
       if (ch == '=') fout << ">=" << " " << "(运算符)" << endl;
       else
       {
        fout << ">" << " " << "(运算符)" << endl;
       }
      }
     else if (ch == '!')
      {
       fin.get(ch);
       if (ch == '=') fout << "!=" << " " << "(运算符)" << endl;
      }
     else if (ch == '(') fout << "(" << " " << "(分隔符)" << endl;
     else if (ch == ')') fout << ")" << " " << "(分隔符)" << endl;
     else if (ch == '{') fout << "{" << " " << "(分隔符)" << endl;
     else if (ch == '}') fout << "}" << " " << "(分隔符)" << endl;
     else if (ch == ',') fout << "," << " " << "(分隔符)" << endl;
     else if (ch == ';') fout << ";" << " " << "(分隔符)" << endl;
     else if (ch == '#') fout << "#" << " " << "(标识符)" << endl;
 }
 ch = '\0';
}

⌨️ 快捷键说明

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