用c++写一个词法分析器
时间: 2023-06-27 10:07:14 浏览: 61
好的,下面是一个简单的 C++ 词法分析器示例:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
using namespace std;
string keywords[32] = { "auto", "break", "case", "char", "const", "continue", "default",
"do", "double", "else", "enum", "extern", "float", "for", "goto",
"if", "int", "long", "register", "return", "short", "signed", "sizeof",
"static", "struct", "switch", "typedef", "union", "unsigned", "void",
"volatile", "while" };
bool isKeyword(string word)
{
for (int i = 0; i < 32; i++)
{
if (keywords[i] == word)
return true;
}
return false;
}
bool isOperator(char ch)
{
char operators[] = "+-*/%=";
for (int i = 0; i < 6; i++)
{
if (ch == operators[i])
return true;
}
return false;
}
bool isDelimiter(char ch)
{
char delimiters[] = "(){}[],.:;?";
for (int i = 0; i < 10; i++)
{
if (ch == delimiters[i])
return true;
}
return false;
}
int main()
{
string input;
cout << "Enter filename: ";
getline(cin, input);
ifstream file;
file.open(input);
if (!file)
{
cout << "Unable to open file!";
exit(1);
}
char ch;
string word;
int line = 1;
while (file >> noskipws >> ch)
{
if (ch == '\n')
line++;
if (isDelimiter(ch))
{
if (word.length() != 0)
{
if (isKeyword(word))
cout << word << " is a keyword" << endl;
else
cout << word << " is an identifier" << endl;
}
cout << ch << " is a delimiter" << endl;
word = "";
}
else if (isOperator(ch))
{
if (word.length() != 0)
{
if (isKeyword(word))
cout << word << " is a keyword" << endl;
else
cout << word << " is an identifier" << endl;
}
cout << ch << " is an operator" << endl;
word = "";
}
else if (isspace(ch))
{
if (ch == '\n')
line++;
if (word.length() != 0)
{
if (isKeyword(word))
cout << word << " is a keyword" << endl;
else
cout << word << " is an identifier" << endl;
word = "";
}
}
else
{
word += ch;
}
}
file.close();
return 0;
}
```
这个词法分析器可以读取一个文件,将其分解为标识符、关键字、操作符和分隔符,并输出它们的类型。