代码:
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include<cstdlib>
using namespace std;
#define MaxQuestions 100//最大问题数量
#define MaxLinesPerQuestion 100//每个问题的最多行数
#define MaxAnswersPerQuestion 10//每个问题最多答案个数
#define EndMarker "------"//末尾分割线
struct answerT
{
string ans; //答案
int nextq; //该答案所对应的下一题的编号
};
struct questionT
{
int nQ; //问题编号
string qText[MaxLinesPerQuestion + 1];//问题文本
answerT answers[MaxAnswersPerQuestion];//当前问题的答案
};
struct courseDB
{
string title;//标题
questionT *questions[MaxQuestions + 1];//问题
};
//初始化
//函数声明
courseDB *ReadDataBase(courseDB *);//读入数据
/*
bool ReadOneQuestion(ifstream &infile, courseDB *course);//读取一个问题
void ReadQuestionText(ifstream &infile96, questionT *q);//读取问题文本
void ReadAnswers(ifstream &infile, questionT *q);//读取该问题的答案
void ProcessCourse(courseDB *course);
*/
void AskQuestion(questionT *q);//提问
int FindAnswer(string ans, questionT *q);//寻找答案
int main()
{
system("color 2e"); //设置颜色
courseDB *read = new courseDB();
*ReadDataBase(read);//读入数据
AskQuestion(read->questions[1]);
delete read;
system("pause");
}
courseDB *ReadDataBase(courseDB *read)
{
cout << "请输入要读取的文件名:";
string filename;
cin >> filename;
ifstream infile(filename, ios::in);
if (!infile)
{
cerr << "open error!" << endl;
exit(1);
}
string Line[MaxLinesPerQuestion+1][MaxQuestions ];
getline(infile, Line[0][0]);
read->title = Line[0][0];
cout << read->title << endl;//标题
for (int i = 1; i <= MaxQuestions; i++)
{
int j = 1;
for (j=1; j <= MaxLinesPerQuestion + 1; j++)
{
getline(infile, Line[i][j]);
stringstream ss;
ss << Line[i][j];
ss >> read->questions[i]->nQ;
if (Line[i][j] == EndMarker)
{
for (int k = j + 1; k <= MaxAnswersPerQuestion; k++)
{
getline(infile, Line[i][k]);
string a, b;
for (unsigned int m = 0; m < sizeof(Line[i][k]) - k; m++)
{
a[m] = Line[i][k][m];
if (Line[i][k][m] == ':')
{
continue;
}
b[m] = Line[i][k][m];
ss <<b;
ss >> read->questions[i]->answers[k-j-1].nextq;
read->questions[i]->answers[k-j-1].ans = a;
}
}
break;
}
}
if (Line[i][j] == "\n\r")continue;//若读入的行为空白行,则跳出本次循环,读入下一题
}
return 0;
}
void AskQuestion(questionT *q)
{
cout << q->qText << endl;
cout << "Please enter your answer:";
string answer;
cin >> answer;
FindAnswer(answer, q);
}
int FindAnswer(string ans, questionT *q)
{
questionT p;
for (int i = 0; i < MaxAnswersPerQuestion; i++)
{
if (ans == q->answers[i].ans)
{
AskQuestion(&p + q->answers[i].nextq);
}
else cout << "Enter error, please re-enter:";
string answer;
FindAnswer(answer, q);
}
return 0;
}
警告(IDE:vs2015)如下:
string Line[MaxLinesPerQuestion+1][MaxQuestions ];
这个太大了,改成动态分配。
string Line[MaxLinesPerQuestion+1][MaxQuestions ]; 这句有问题,string本来就相当于stl,还需要使用这样的数组么,循环 嵌套也太多了,效率很低,最好封装
几个接口来访问,或者几个函数
我看了一下...你的courseDB *read = new courseDB(); 你的courseDB中的*questions[MaxQuestions 1]没有分配到内存,所以ss>>read->questions[i]->nQ,就会报错,在这一句前面加上read->questions[i]=new questionT;给它分配内存就好.
如果解决了,就采纳吧