您如何通过忽略具有单个字符的单独行来从文件中读取单独的整数行?

How do you read separate lines of integers from file by ignoring separate lines with a single character?

我正在开发一个处理二叉搜索树的程序。我有一个简单的文本文件,如下所示:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
$
5 4 3 5 7 13
$
11 6 7 2 12 6

第一行是要插入树的整数,第三行是要查找的整数,第五行是要取出的整数。第二行和第四行是为了标记其他行的分隔。它们包含单个字符“$”。 我正在为如何忽略第二行和第四行而苦苦挣扎。我有三个 while 循环,用两个忽略语句分隔。经过测试,似乎从未进入第二个和第三个 while 循环。如果有任何帮助,我将不胜感激 - 我的代码如下。

#include <iostream>
#include <cstdlib>
#include <string>
#include <fstream>
#include "main.h"


int main(int argc, char *argv[])
{    
    string filename = "";
    ifstream inFile;

    filename = argv[1];
    inFile.open(filename.c_str());

    BST b;
    int num;

    while(inFile >> num)
    {
       b.insert(num);
       cout << num << endl; //output testing - the first line was successfully output so I think this part is fine
    }

    inFile.ignore(500, '$');

    while(inFile >> num) //this while loop is never entered
    {
        b.search(num);
    }
    inFile.ignore(500, '\n');

    while(inFile >> num) //this while loop is never entered
    {
        b.remove(num);
    }

    inFile.close();  
}

完成读取数字的循环后,添加一行以清除输入流的错误状态。没有它,就不会执行后续的读取操作。

while(inFile >> num)
{
   b.insert(num);
   cout << num << endl; //output testing - the first line was successfully output so I think this part is fine
}

inFile.clear();           // ADD THIS LINE
inFile.ignore(500, '$');

while(inFile >> num) //this while loop is never entered
{
    b.search(num);
}

inFile.clear();           // ADD THIS LINE
inFile.ignore(500, '\n');