一位用户在今天早些时候发布了一个类似的问题,由于其含糊不清,很快就关闭了。因此,通过解决方案重新发布问题,因为我没有找到在互联网上处理它的具体文章。
要求是读取并打印除最后一个K之外的所有文件行。
假设文件包含以下文本:
Hello there!
My name is
Mr. XYZ
I like playing football
如果K是2,那么它应该打印除最后2之外的所有行。即:
Hello there!
My name is
答案 0 :(得分:1)
这可以通过创建大小为K的窗口然后遍历文件直到窗口的右端到达文件末尾来轻松解决。基本步骤是:
遍历文件的前K行而不打印它。
使用其他流对象打开同一文件。
现在同时遍历两个流,以便fisrt流始终位于第二个流之前的K行。
在第二个第一个流有效时运行循环。在循环中,也要读取第一个流并继续打印行。
代码是
#include<iostream>
#include<fstream>
#include<string>
int main()
{
fstream fs;
fs.open("abc.txt",ios::in);
string str;
int K = 2;
while(getline(fs,str) && K>1)
{
K--;
}
if(K==1)
{
fstream fsNew;
fsNew.open("abc.txt",ios::in);
while(getline(fs,str))
{
getline(fsNew,str);
cout<<str;
}
}
cin.ignore();
}
答案 1 :(得分:1)
为什么不简单地将行放入std::deque
并在其大小为k
时转储一个元素?
#include<iostream>
#include<fstream>
#include<deque>
int main()
{
std::fstream fs;
fs.open("output.txt",std::ios::in);
std::deque<std::string> deq;
std::string str;
int k=2;
while(std::getline(fs,str))
{
deq.push_back(str);
if(deq.size() > k)
{
std::cout <<deq.front()<<std::endl;
deq.pop_front();
}
}
}