无法从输入文件中读取单个字符

时间:2014-02-27 03:39:15

标签: c++

我正在尝试从单个输入文件创建多个二叉树。输入文件类似于:

ABCDEFG

JUHSKDHFG

HDSNURHLNF

JNDKFJBJNF

每一行代表一个不同的树,所以我必须分别阅读每个字符。我现在的代码只读取每行的第一个字母,并在第一个字母中创建一个树。如何将整行读作一棵树,然后用下一行重新开始?

这是我现在的代码:

 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 个答案:

答案 0 :(得分:0)

尝试更像这样的东西:

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;
}