文件读入LR(1)分析表代码c++
时间: 2023-11-30 08:03:44 浏览: 34
下面是使用C++语言实现文件读入LR(1)分析表的示例代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
int main() {
// 打开LR(1)分析表文件
ifstream infile("lr1_table.txt");
if (!infile) {
cerr << "Error: failed to open lr1_table.txt" << endl;
return 1;
}
// 读取终结符和非终结符列表
string line;
getline(infile, line);
vector<string> terminals;
stringstream ss(line);
string term;
while (getline(ss, term, ' ')) {
terminals.push_back(term);
}
getline(infile, line);
vector<string> non_terminals;
ss.str(line);
while (getline(ss, term, ' ')) {
non_terminals.push_back(term);
}
// 构建ACTION表和GOTO表
unordered_map<pair<int, string>, int> action_table;
unordered_map<pair<int, string>, int> goto_table;
int state;
string action;
int target;
while (infile >> state >> action >> target) {
if (find(terminals.begin(), terminals.end(), action) != terminals.end()) {
action_table[make_pair(state, action)] = target;
} else {
goto_table[make_pair(state, action)] = target;
}
}
// 打印ACTION表和GOTO表
cout << "ACTION表:" << endl;
for (auto it : action_table) {
cout << it.first.first << " " << it.first.second << " " << it.second << endl;
}
cout << "GOTO表:" << endl;
for (auto it : goto_table) {
cout << it.first.first << " " << it.first.second << " " << it.second << endl;
}
return 0;
}
```
在上述代码中,假设LR(1)分析表文件的格式与前面Python示例代码中介绍的格式相同。代码使用C++的STL库中的unordered_map容器存储ACTION表和GOTO表。首先打开文件并读取终结符和非终结符列表,然后依次读取每行内容,并根据动作是终结符还是非终结符将其添加到ACTION表或GOTO表中。最后打印ACTION表和GOTO表。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)