0

I am trying to create multiple binary trees from a single input file. The input file looks something like:

ABCDEFG

JUHSKDHFG

HDSNURHLNF

JNDKFJBJNF

Each line represents a different tree, so I have to read in each character individually. The code I have now only reads the first letter of each line and creates a single tree out of the first letter. How do I read the whole line as one tree, then start over again with the next line?

This is the code I have right now:

 int main()
    {
        BinaryTree <char> BT;
        char ch;
        string line;
        ifstream myfile("input.txt");
        if (myfile.is_open())
        {
            while(getline(myfile, line)
            {
                while(myfile.get(ch))
                {
                    BT.InsertData(ch);
                    if(ch = '\n')
                        break;
                }
            }    
            cout << "Preorder: ";
            BT.PrintPreorder();
            cout << endl;
            cout << "Inorder: ";
            BT.PrintInorder();
            cout << endl;
            cout << "Postorder: ";
            BT.PrintPostorder();
            cout << endl;
            cout << "Reverse Inorder: ";
            BT.PrintReverseInorder();
            cout << endl;    
            BT.PrintPrintTree();
            cout << endl;    
            myfile.close();
        }
        return 0;
    }
1
  • 1
    And... ? A question? Is it your intent to ignore every line with actual data and finish each outer-loop pass with tree with a single newline? given your input data, that appears to be what will happen.
    – WhozCraig
    Feb 27, 2014 at 3:43

1 Answer 1

0

Try something more like this instead:

int main()
{
    string line;
    ifstream myfile("input.txt");
    if (myfile.is_open())
    {
        while (getline(myfile, line))
        {
            if (line.empty())
                continue;

            BinaryTree <char> BT;
            for(string::iterator iter = line.begin(); iter != line.end(); ++iter)
                BT.InsertData(*iter);

            cout << "Preorder: ";
            BT.PrintPreorder();
            cout << endl;
            cout << "Inorder: ";
            BT.PrintInorder();
            cout << endl;
            cout << "Postorder: ";
            BT.PrintPostorder();
            cout << endl;
            cout << "Reverse Inorder: ";
            BT.PrintReverseInorder();
            cout << endl;    
            BT.PrintPrintTree();
            cout << endl;    
        }    
    }
    return 0;
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.