您的位置:首页 > 编程语言 > C语言/C++

编程实现计算FIRST集和FOLLOW集C++之(一)处理候选式:多个右部

2016-05-24 17:42 441 查看
当前目录下有这三个文件

houxuanshi_processed.txt
houxuanshi.txt
main.cpp


houxuanshi.txt的内容

E->TE'
E'->+TE'|ε
T->FT'
T'->*FT|ε
F->(E)|id


开始houxuanshi_processed.txt 内容是空的或者直接没有这个文件。

main.cpp

#include<fstream>
#include<iostream>
#include<string>
#include<vector>
/*
*实现编译原理语法分析中计算非终结符的First集Follow集
*候选式存于文件中
*
*/
using namespace std;
//定义候选式类
class HXS{
public:
string left;
vector<string> right;
};
/*
*把有多个右部的候选式切分开,便于下一步进行处理
*/
void split(){
string line;
string symor("|");
size_t found;
ifstream infile("houxuanshi.txt");
ofstream processed("houxuanshi_processed.txt");
if(!infile.is_open()){
cout << "Error Open File!" << endl;
}
cout << "------------------------" << endl;
cout << "候选式:" << endl;
line = "";
while(getline(infile,line)){
cout << line << endl;
found =  line.find(symor);
if(found == string::npos){
processed << line << endl;
continue;
}else{
cout << "Has | " << endl;
processed << line.substr(0,found) << endl;
processed << line.substr(0,line.find(">")+1)+line.substr(found+1,line.length()-found) << endl;
}
line = "";
}
cout << "------------------------" << endl;
infile.close();
processed.close();
}
int main(){
split();
}


执行

g++ main.cpp
./a.out


houxuanshi_processed.txt被创建,并写入了内容

E->TE'
E'->+TE'
E'->ε
T->FT'
T'->*FT
T'->ε
F->(E)
F->id


这里主要是split函数,使用了c++的string的各种字符串操作。

这样处理了候选式之后,就便于程序进一步分析每一个候选式的特征,从而计算非终结符的FIRST集和FOLLOW集。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息