[英]Trouble reading input from txt file 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);
}
};
创建BinaryTrees的向量/数组,然后将其推回到while(getline(myfile,line,''))循环中。
int main() {
vector <BinaryTree <string> > BT;
int iteration = 0;
string line;
ifstream myfile("input.txt");
if (myfile.is_open())
{
while(getline (myfile, line))
{
BinaryTree <string> temptree;
BT.push_back(temptree);
BT[iteration].InsertData(line);
cout << "Preorder: ";
BT[iteration].PrintPreorder();
cout << endl;
cout << "Inorder: ";
BT[iteration].PrintInorder();
cout << endl;
cout << "Postorder: ";
BT[iteration].PrintPostorder();
cout << endl;
cout << "Reverse Inorder: ";
BT[iteration].PrintReverseInorder();
cout << endl;
BT[iteration].PrintPrintTree();
cout << endl;
iteration++;
}
myfile.close();
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.