c++识别标识符

#include "stdafx.h"
#include <iostream> 
#include "string.h"  
#define N 15   
using namespace std;
struct TokenType
{
int code, value;
};
char *keywords[] = { "program","procedure","begin","end","while","return","int","+","*",":",":=","=",",",";","(",")","<",">" };
char fuhao[10][10];
int m;
int changshu[10];
int n;


int IsLetter(char ch)
{
if (ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z')
return 1;
else
return 0;
}
int IsDigit(char ch)
{
if (ch >= '0' && ch <= '9')
return 1;
else
return 0;
}
int Reserve(char *strToken)
{
int i = 0;
while (i<N)
{
if (!strcmp(keywords[i], strToken))
return (i + 3);
i++;
}
return 0;
}
int InsertID(char *strToken)
{
int i = 0;
while (i<m)
{
if (!strcmp(fuhao[i], strToken))
return i;
i++;
}
strcpy_s(fuhao[i], strToken);
m++;
return i;
}
int trans(char *str)
{
int num, i;
num = i = 0;
while (str[i])
num = 10 * num + str[i++] - 48;
return num;
}
int InsertConst(char *strToken)
{
int i = 0;
int num;
num = trans(strToken);
while (i<n)
{
if (changshu[i] == num)
return i;
i++;
}
changshu[i] = num;
n++;
return i;
}
int main()
{
char jiancechuan[] = "public static void main (String [] args) { double sum5 = 0.0;for (int i = 1; i<5; i++) {sum5 = sum5 + (i + 10);sum5 = sum5 + (i * 2);}}";
int jccwz;
char ch;
char strToken[15];
int strwz;
int code, value;
int i = 0;
jccwz = 0;
ch = jiancechuan[jccwz++];
while (ch)
{
strwz = 0;
while (ch == ' ')
ch = jiancechuan[jccwz++];
if (IsLetter(ch))
{
while (IsLetter(ch) || IsDigit(ch))
{
strToken[strwz++] = ch;
ch = jiancechuan[jccwz++];
}
jccwz--;
strToken[strwz] = '\0';
code = Reserve(strToken);
if (!code)
{
value = InsertID(strToken);
cout << "(\"" << strToken << "\"," << 1 << ")" << endl;
}
else
{
cout << "(\"" << strToken << "\"," << code << ")" << endl;
}
}
else if (IsDigit(ch))
{
while (IsDigit(ch))
{
strToken[strwz++] = ch;
ch = jiancechuan[jccwz++];
}
jccwz--;
strToken[strwz] = value = InsertConst(strToken);
cout << "(\"" << strToken << "\"," << "2)" << endl;
}
else
{
strToken[strwz++] = ch;
if (ch == ':')
{
ch = jiancechuan[jccwz++];
if (ch == '=')
strToken[strwz++] = ch;
else
jccwz--;
}
strToken[strwz] = '\0';
code = Reserve(strToken);
if (code)
{
cout << "(\"" << strToken << "\"," << code << ")" << endl;
}
}
ch = jiancechuan[jccwz++];
}
cout << "符号表内容:" << endl;
for (i = 0; i<m; i++)
cout << fuhao[i] << endl;
cout << "常数表内容:" << endl;
for (i = 0; i<n; i++)
cout << changshu[i] << endl;
return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值