?? compiler.cpp
字號:
#include <iostream.h>
#include <string.h>
#include <stdio.h>
#include <process.h>
int i,j;
char c[20];
FILE *fp;
FILE *result;
int compare1(char ch) //compare single character
{
if ('0'<=ch&&ch<='9')
return 1; //digit
else
if (('A'<=ch&&ch<='Z')||('a'<=ch&&ch<='z'))
return 2; //letter
else
return 0; //other
}
int compare2(char *c) //keywords and symbol
{
if(strcmp(c,"main")&&strcmp(c,"if")&&strcmp(c,"then")&&strcmp(c,"else")&&strcmp(c,"while")&&strcmp(c,"do")&&strcmp(c,"int"))
return 1;
else
return 0; // same means 0
}
void scan(char &ch)
{
if(compare1(ch)==2) //1st character is letter
{
i=1;
c[0]=ch;
ch=fgetc(fp);
while(compare1(ch)>0)
{
c[i++]=ch;
ch=fgetc(fp);
}
c[i]='\0';
if (!compare2(c))
{
cout<<"<"<<c<<",->"<<endl; //keyword
fprintf(result,"<%s,->\n",c);
}
else
{
cout<<"<0,"<<c<<">"<<endl; //symbol
fprintf(result,"<0,%s>\n",c);
}
}
else if(compare1(ch)==1) //1st char is digit then it is number
{
if('1'<=ch&&ch<='9') //1st char is 1-9 means decimal (10 based)
{
j=1;
c[0]=ch;
ch=fgetc(fp);
i=1;
while(compare1(ch)==1)
{
c[i++]=ch;
ch=fgetc(fp);
}
c[i]='\0';
}
else if(ch=='0') //1st char is 0 means 8/16 based
{
ch=fgetc(fp); // point to 2nd char
//if(compare1(ch)==1) //if 2nd char is digit then >0 or else =0
i=0;
if(ch=='x')
{
ch=fgetc(fp);
j=3;
while(compare1(ch)==1||(ch<='f'&&ch>='a'))
{
c[i++]=ch;
ch=fgetc(fp);
}
c[i]='\0';
} //2nd char is x means 16 based or else 8 based
else if(compare1(ch)==1)
{
j=2; //8-base means type 2
while(compare1(ch)==1)
{
c[i++]=ch;
ch=fgetc(fp);
}
c[i]='\0';
}
else
{
j=0;
ch='0';
i=1;
cout<<"<1,0>"<<endl;
fprintf(result,"<%d,%s>\n",i,c);
ch=fgetc(fp);
}
}
if(j)
{
cout<<"<"<<j<<","<<c<<">"<<endl; //output value
fprintf(result,"<%d,%s>\n",j,c);
}
}
else if (ch!=' '&&ch!='\n'&&ch!='\t')
{
cout<<"<"<<ch<<",->"<<endl;
fprintf(result,"<%c,->\n",ch);
ch=fgetc(fp);
}
else ch=fgetc(fp);
}
void main ()
{
char ch;
if((fp=fopen("system.txt","r"))==NULL)
{
printf("<system.txt> not opened.\n");
exit(0);
}
result=fopen("result.txt","w");
ch=fgetc(fp);
while(ch!=EOF)
scan(ch);
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -