为什么在程序中有一个while循环之前,第二个while循环为什么不起作用?

时间:2019-06-26 23:37:06

标签: c++ file loops while-loop text-files

while循环均单独工作。但是,当上面的while循环存在时,我的代码中的第二个while循环将不起作用。我需要两个while循环才能一起工作。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main(){
    string line, line1, line2;
    int count = 0;
    int track = 0;
    int stop;
    ifstream file ("ai.txt");
    while (getline(file, line2)){
        count++;
    }
    file.seekg (0L, ios :: beg);
    stop = count - 10;
    while (getline(file, line)){
        track++;
        if (track >= stop){
            for (int num = 1; num <=10; num++){
                getline(file,line1);
                cout << line1 << endl;   
            }
        }
    }

}

该代码应输出任何文本文件的最后十行。

1 个答案:

答案 0 :(得分:2)

因此,您消耗了文件流中的所有行。

然后,您将流搜索回到文件的开头。

您又开始使用行了。

您没有做的是从流第一次到达末尾时设置的流中清除“文件结束”标志。在那个标志仍然存在的情况下,流是无用的。

file.clear()之前添加file.seekg(...)

相关问题