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

📄 zhangshiying.cpp

📁 能实现对输入字符的词法分析,但不太完善,还需要进一步完善,结果中会出现毛病.
💻 CPP
字号:
#include <process.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <malloc.h>
#include <ctype.h>
#include <conio.h>
FILE *fp;
char ch;
char *keyword[]={"do","begin","if","else","for","while","int","char","float","double"};
char *limit[]={",",";","(",")","{","}","()"};
char *process[]={"+","-","*","/","<","<=","=",">",">=","!=",":=",".","&","&&","%","_"} ;

 char bsfb[100][20];       /*用于存放源代码*/
 char  numb[100][20];

 static int countb=0;

int search(char a[],int type)
{
 int i;
 switch (type)
 {
 case 0:
     for(i=0;i<10;i++)          /*判断是否为关键字,是则返回1*/
     {
      if(strcmp(keyword[i],a)==0)
       return(1);            
      }
     break;
 case 1:
    for(i=0;i<7;i++)         /*若是分隔符,则返回1 */
    {
     if(strcmp(limit[i],a)==0)
      return(1);
    }
    break;
case 2:
    for(i=0;i<16;i++)           /*若是运算符,则返回1*/
    {
     if(strcmp(process[i],a)==0)
      return(1);
    }
    break;

 }
 return(0);
}





char letterprocess (char ch)
{
 int i=0;
 char letter[20];
 while ((isalnum(ch)!=0)||(ch=='_'))
 {
  letter[i++]=ch;
  ch=fgetc(fp);   
 };

  letter[i]='\0';
 if (search(letter,0))
 {
  printf(" 关键字    %s   \n",letter);

 }
 else
 {
  printf(" 标识符      %s   \n",letter);
 
  strcpy(bsfb[countb++],letter);
 }
return(ch);
}




char numberprocess(char ch)
{
 int i=0;
 char num[20];
 while((isdigit(ch)!=0)||(ch=='.'))
 {
  num[i++]=ch;
  ch=fgetc(fp);
 }

 if(isalpha(ch)!=0) 
 {
  while(isspace(ch)==0)
  {
            num[i++]=ch;
            ch=fgetc(fp);
  }

  num[i]='\0';
  printf("   常数  %s   \n",num);
return(ch);
 }
    num[i]='\0';
    printf("  常数    %s   >\n",num);

 return(ch);
}




char otherprocess(char ch)
{
 int i=0;
 char other[20];
 if (isspace(ch)!=0)
 {
  ch=fgetc(fp);
  return (ch);
 }
 while ((isspace(ch)==0)&&(isalnum(ch)==0))
 {
  other[i++]=ch;
  ch=fgetc(fp);
 }
 other[i]='\0';
 if (search(other,1))
  printf("  分隔符        %s   \n",other);
 else
     if (search(other,2))
         printf("   运算符      %s   \n",other);
else
     printf("  其他     %s   \n",other);
 return (ch);
}



void main ()
{
 char str,c;
 int i=0;
       /*在此用字符数组接受字符串*/
 if ((fp=fopen("zhangshiying.txt","r"))==NULL)
  printf("no such a file\n");
 else
 {/*用while循环遍历字符数组*/
  str =fgetc(fp);
  while (str!=EOF)  
  {
     if ((isalpha(str)!=0)||(str=='_'))       /*如果是字母或下划线*/
    str=letterprocess(str);                   /*调用letterprocess()函数*/
   else
   {
    if (isdigit(str)!=0)                     /*如果是数字*/
     str=numberprocess(str);
    else                                     /*如果既不是字母又不是下划线还不是数字*/
     str=otherprocess(str);
   }
    
  }; 
  printf("\n");
 for(i=0;i<countb;i++)
  {
      printf("%s\n",bsfb[i]);
  }
 }
  c=getch();
}

⌨️ 快捷键说明

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