我無法從文本文件讀取輸入。我想要做的是從一個輸入文件打印多個二叉樹。我想爲輸入的每一行打印一個新的二叉樹,但我不確定如何。目前它只是將整個文件作爲一棵樹讀取。無法從txt文件讀取輸入C++
我的輸入文件的一個例子是:
ABCDEFG
BHYTGFHJU
KIJUTTEDS
JHYGFOKJHSG
,這裏是我的代碼的一部分,我相信問題在於:
int main()
{
BinaryTree <string> BT;
string line;
ifstream myfile("input.txt");
if (myfile.is_open())
{
while(getline (myfile, line, ' '))
{
BT.InsertData(line);
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;
}
編輯:如在我的評論中問,這是我的BinaryTree類代碼。
template <class T>
class BinaryTree
{
private:
struct TreeNode
{
TreeNode *left;
TreeNode *right;
T data;
};
TreeNode *root;
public:
BinaryTree()
{
root = NULL;
}
void Inorder(TreeNode *n)
{
if(n != NULL)
{
Inorder(n -> left);
cout<< n -> data;
Inorder(n -> right);
}
}
void PrintInorder()
{
Inorder(root);
}
void Preorder(TreeNode *n)
{
if(n != NULL)
{
cout<< n -> data;
Preorder(n -> left);
Preorder(n -> right);
}
}
void PrintPreorder()
{
Preorder(root);
}
void Postorder(TreeNode *n)
{
if(n != NULL)
{
Postorder(n -> left);
Postorder(n -> right);
cout<<n -> data;
}
}
void PrintPostorder()
{
Postorder(root);
}
void ReverseInorder(TreeNode *n)
{
if(n != NULL)
{
ReverseInorder(n -> right);
cout<< n -> data;
ReverseInorder(n -> left);
}
}
void PrintReverseInorder()
{
ReverseInorder(root);
}
void PrintTree(TreeNode* n, int lev)
{
if (n != NULL)
{
PrintTree(n -> right, lev+1);
for (int i=0; i<lev; i++)
cout << "\t";
cout << n -> data << endl;
PrintTree(n -> left, lev+1);
}
}
void InsertData(T data)
{
TreeNode *t = new TreeNode;
TreeNode *parent;
t -> data = data;
t -> left = NULL;
t -> right = NULL;
parent = NULL;
//is this a new tree?
if (isEmpty())
root = t;
else
{
TreeNode *curr;
curr = root;
while(curr)
{
parent = curr;
if (t -> data > curr -> data)
curr = curr -> right;
else
curr = curr -> left;
}
if(t -> data < parent -> data)
parent -> left = t;
else
parent -> right =t;
}
}
void PrintPrintTree()
{
PrintTree(root, 0);
}
bool isEmpty()
{
return (root == NULL);
}
};
什麼問題?對我來說似乎很好。 – herohuyongtao
對我來說看起來不錯..但是當我運行該程序時,它將整個輸入文件作爲一棵樹讀取,並且只在打印出多個時纔打印出一棵樹。 – user3335367
如何定義「BinaryTree」? – herohuyongtao