这两个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;
}
}
}
}
代码应该输出任何文本文件的最后十行。
发布于 2019-06-27 07:46:54
所以你消耗了一个文件流中的所有行。
然后,您查找返回到文件开头的流。
你又开始使用lines了。
您没有做的是从第一次到达末尾时设置的流中清除"end of file“标志。那面旗子还在的时候,流就没用了。
在file.seekg(...)
之前添加file.clear()
。
https://stackoverflow.com/questions/56782183
复制相似问题