while ((in_char = GetNextChar()) != EOF)
{
while (in_char == '\t' || in_char == '\n' || in_char == ' ')
{
in_char = GetNextChar();
}
//数字
if (isdigit(in_char))
{
do
{
token_string += in_char;
in_char = GetNextChar();
}while (isdigit(in_char));
UngetNextChar(in_char);
token = NUM;
}
//ID OR reserved word
else if (isalpha(in_char))
{
do
{
token_string += in_char;;
token_length ++;
in_char = GetNextChar();
}while (isalpha(in_char) && (token_length < max_token_length));
UngetNextChar(in_char);
token = CheckReserved();
}
//是否是赋值符号
else if (in_char == ':')
{
token_string += in_char;
in_char = GetNextChar();
if (in_char == '=')
{
token = ASSIGNOP;
}
else
{
UngetNextChar(in_char);
token = COLON;
}
}
//其它符号
else
{
switch (in_char)
{
case EOF:
token = ENDFILE;
break;
case '=':
token = EQ;
break;
/////////////////////////////////////////////////////////
//未支持 >= <=
case '<':
token = LT;
break;
case '>':
token = GT;
break;
////////////////////////////////////////////////////////
case '+':
token = PLUSOP;
break;
case '-':
token = SUBOP;
break;
case '*':
token = MULOP;
break;
case '/':
token = DIVOP;
break;
case '(':
token = LPAREN;
break;
case ')':
token = RPAREN;
break;
case ';':
token = SEMI;
break;
case ',':
token = COMMA;
break;
case '#':
token = SHARP;
break;
case '.':
token = ENDFILE;///////////////////////
break;
default:
fprintf(listing, "Unknown : %d\n", in_char);
token = ENDFILE;
break;
}
}
break;
}
return token;
}
#endif
测试程序:
#include "Scanner.h"
int main()
{
Scanner scan("testPas.txt");
scan.SetReserved();
scan.ShowReserved();
scan.ShowAllTokens();
return 0;
}
测试文件:
const a=10;
var b,c;
procedure p;
var d;
begin
d:=20;
c:=d/a;
c:=c+b;
end;
begin
read (b);
while b#0 do
begin
call p;
write(2*c);
read(b);
end
end.