📄 trangrammar.cpp
字号:
#include <sstream>
#include "parse.h"
#include "read.h"
extern ifstream grammarfile;
extern DVec_str productions;
extern vecStr terminals;
extern vecNter nonterminals;
void readGrammar(void)
{
string name = "grammar.txt";
Nonterminal nonterminal;
grammarfile.open( name.c_str() );
if( !grammarfile ) cout << "Cannot open the source grammar file!";
ofstream outf( "tokens.txt" );
if( !outf ) cout << "Cannot open the file " << "token.txt!\n";
readfile(grammarfile,productions);
for(size_t i = 0;i < productions.size();i++) // make the nonterminals
{
nonterminal.token = productions[i][0];
if( !hasexisted( nonterminals,nonterminal ) ) nonterminals.push_back( nonterminal );
}
for(size_t i = 0;i < productions.size();i++) //make the terminals
for(size_t j = 1;j < productions[i].size() ;j++)
{
nonterminal.token = productions[i][j];
if( !hasexisted(terminals,productions[i][j]) && !hasexisted(nonterminals,nonterminal) )
terminals.push_back(productions[i][j] );
}
outf <<"The terminals has:\n";
for(size_t i=0;i<terminals.size();i++)
outf<<terminals[i]<<"\n";
outf <<"\n\nThe nonterminals has:\n";
for(size_t i=0;i<nonterminals.size();i++)
outf<<nonterminals[i].token<<"\n";
outf.close();
name = "grammar_tran.txt";outf.open( name.c_str() );
if( !outf ) cout << "Cannot open the file gmar_no|.txt!\n";
else printPro( outf );
}
bool hasexisted( vector< string> vec ,string str )
{
size_t i;
for(i = 0;i < vec.size() && str != vec[i];i++);
return i == vec.size() ? false : true;
}
bool hasexisted( vector< Nonterminal > vec ,Nonterminal n)
{
size_t i;
for(i = 0;i < vec.size() && n.token != vec[i].token;i++);
return i == vec.size() ? false : true;
}
void readfile(ifstream &inf,DVec_str &productions)
{
string str,strline;
while( getline(inf,strline) )
{
vecStr production;
istringstream sin( strline );
while( sin >> str )
{
if( str !="→" && str != "|" )
production.push_back( str );
else if( str == "→" ) ;//sin.seekg(1,ios_base::cur );
else
{
productions.push_back( production );
str = production[0];
production.clear();
production.push_back(str );
}
}
productions.push_back( production );
}
}
void printPro(ofstream &outf )
{
for(size_t i = 0;i < productions.size();i++)
{
outf << productions[i][0] << " → " ;
for( size_t j = 1;j < productions[i].size();j++)
{
outf << productions[i][j] << " ";
}
outf << endl;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -