【问题标题】:Why does the second while loop in my program not work when there is a while loop before it?为什么我的程序中的第二个while循环在它之前有一个while循环时不起作用?
【发布时间】:2019-11-08 22:52:21
【问题描述】:

两个 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;   
            }
        }
    }

}

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

【问题讨论】:

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


    【解决方案1】:

    所以你消耗了文件流中的所有行。

    然后您将流返回到文件的开头。

    然后你又开始消耗线了。

    您没有做的是从第一次到达末尾时设置的流中清除“文件结尾”标志。那个标志还在,流就没有用了。

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

    【讨论】:

      猜你喜欢
      • 2022-12-12
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多