我试图通过从单个txt文件中读取来创建多个二叉树。为此,我必须读取一行中的每个字符,创建树,然后移动到下一行以创建另一个树。我目前的代码是逐行获取输入,我不知道如何更改它?
这就是我现在所拥有的:
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;
}
答案 0 :(得分:0)
char c;
while (myfile>> std::noskipws >> c)
{
if(c == '\n')
printf("new line\n");
printf("%c\n", c);
}
使用operator>>
逐字符读取,然后测试是否有换行符,std::noskipws
表示初始空格字符是要提取的有效内容。或者你也可以像这样使用ifstream.get()
:
char c;
while (myfile.get(c))
{
if(c == '\n')
printf("new line\n");
printf("%c\n", c);
}