1)函数声明
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <iomanip>
using namespace std;
struct FamilyTreeNode{
string name;
vector<FamilyTreeNode * > child;
};
FamilyTreeNode * readFamilyTree(string filename);
void error(string msg);
string getParent(string line);
string getChild(string line);
void insertNode(FamilyTreeNode *&t, string parent, string child);
void showFamily(FamilyTreeNode *t, int order);
2)主函数
int main()
{
cout << "Hello World!" << endl;
FamilyTreeNode *t = readFamilyTree("normandy.dat");
showFamily(t, 0);
return 0;
}
3)读入文件,输出一个家族树(文件的格式 每行 child:parent 并且第一行必须包含家族树树的根节点, 每一行中的parent必须在前面出现过)
FamilyTreeNode *readFamilyTree(string filename){
string base = "D:\\QT\\familyTree\\";
ifstream infile;
infile.open(base + filename);
if (infile.fail()){
error("filename is wrong");
}
FamilyTreeNode *t = NULL;
while(!infile.eof()){
string line;
getline(infile, line);
string parent = getParent(line);
string child = getChild(line);
cout << parent << "|||" << child << endl;
insertNode(t, parent, child);
}
return t;
}
void error(string msg){
cerr << msg;
exit(EXIT_FAILURE);
}
string getChild(string line){
string child = "";
for(int i = 0; i < line.size(); i++){
if (line[i] == ':')
break;
child += line[i];
}
return child;
}
string getParent(string line){
string parent = "";
int start = -1;
for(int i = 0; i < line.size(); i++){
if (line[i] == ':')
start = 0;
else if(start == 0){parent += line[i];}
}
return parent;
}
void insertNode(FamilyTreeNode *&t, string parent, string child){
if (t == NULL){
t = new FamilyTreeNode;
FamilyTreeNode *c = new FamilyTreeNode;
t->name = parent;
c->name = child;
t->child.push_back(c);
}
else if (t->name == parent){
FamilyTreeNode *c = new FamilyTreeNode;
c->name = child;
t->child.push_back(c);
}
else{
for (int i = 0; i < t->child.size(); i++){
insertNode(t->child[i], parent, child);
}
}
}
void showFamily(FamilyTreeNode *t, int order){
if (t == NULL){
cout << "there is no family to show.";
}
else{
cout << string(order * 4, ' ') << t->name << endl;
for (int i = 0; i < t->child.size(); i++){
showFamily(t->child[i],order + 1);
}
}
}