/*
*功能:簡單的語法分析器
*作者:王文堃
*創建時間:2016/4/5
*/
//根據輸入判斷語法是否正確
//文法是:S->cAd A->ab|a
//輸入是:cad,cabd
//預計輸出是:正確
#include<iostream>
using namespace std;
#define MAXSIZE 10
//函數聲明
void GetNextChar();
int S();
int A();
void init_sentence();
void show_sentence();
//程序中需要用到的全局變量
char sentence[MAXSIZE] = {'\0'}; //用來接收輸入的字符串
int ip = 0; //用來指定字符串的下標
//將數組下標加一
void GetNextChar()
{
ip++;
}
//根據每一非終結符對應一個遞歸子函數,函數中應有S,A兩個子函數
//S()針對S->cAd文法
int S()
{
if (sentence[ip] == 'c') //判斷輸入第一個字符是不是c
{
GetNextChar();
if (1 == A()) //文法中第二個A匹配成功
{
if (sentence[ip] == 'd')
{
GetNextChar();
return 1; //成功
}
}
return 0; //文法中A沒有匹配成功
}
return 0; //若第一個字符不是c就返回0
}
//A()針對A->ab|a這種文法
int A()
{
int oldip = ip; //保存ip的值用來回溯
if (sentence[ip] == 'a')
{
GetNextChar();
if (sentence[ip] == 'b')
{
GetNextChar();
return 1; //成功A->ab
}
}
//回溯
ip = oldip;
if (sentence[ip] == 'a')
{
GetNextChar();
return 1; //成功A->a
}
return 0;
}
//從文件中讀取輸入到sentence中
void init_sentence()
{
FILE *pFile;
char ch;
int i = 0;
pFile = fopen("sentence.txt", "r");
ch = fgetc(pFile);
while (ch != EOF)
{
sentence[i++] = ch;
ch = fgetc(pFile);
}
}
void show_sentence()
{
int i = 0;
while(sentence[i] != '\0')
cout << sentence[i++];
cout << endl;
}
void main()
{
init_sentence();
show_sentence();
cout << "檢查結果是:" << endl;
if (1 == S())
cout << "語法正確" << endl;
else
cout << "語法錯誤" << endl;
getchar();
}
文本名字爲:sentence.txt
文本內容爲:cad
將文本放置在與.cpp同目錄下
注:源程序中描述的很清楚,此處不在贅述,功能十分單一供初學者參考,如有不明白的地方或者需要源文件的請聯繫:[email protected]