Creating Binary Tree from a file.

I am trying to get the program to read a text file that has question and answers and depending on the response, moves to the (preorder) node. I get the program to read it, but I am having trouble creating the tree. I don't know how to create another node after the root. It keeps taking ifYes & ifNo as answers only, so it can't ask another question. Here what I've got so far. Its an implementation of the animal game(i.e. "Q Does it live in the water?"). Any help would be greatly appreciated. Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
string line;
        getline(in, line);
        line.erase(0, 1);
        line.erase(0, line.find_first_not_of(' '));
        t = new node(line, 0, 0);
        while(in){
            getline(in, line);
            //cout << line << endl;
            if(line[0] == 'Q'){
                line.erase(0, 1);
                line.erase(0, line.find_first_not_of(' '));
                string nextQuestion = line;
                t->ifYes = new node(nextQuestion, 0, 0);
            }
            else if(line[0] == 'A'){
                line.erase(0, 1);
                line.erase(0, line.find_first_not_of(' '));
                string answer = line;
                t->ifNo = new node(answer, 0, 0);
            }


Here are the declarations:

1
2
3
4
5
6
7
8
struct node {
  std::string question;
  node* ifYes;
  node* ifNo;

  node (std::string q, node* yes = NULL, node* no = NULL)
    : question(q), ifYes(yes), ifNo(no)
    {}
Last edited on
closed account (Dy7SLyTq)
Well it looks like ur erasing the q/a so the first character will be whatever the question starts with
Topic archived. No new replies allowed.