c++ - 使用输入 C++ 从 .txt 文件中打印 N 行
问题描述
我想制作一个从 .txt 读取行的程序,如下所示:
输入:文件名/要开始打印的行/要打印的最后一行数
在控制台中,它看起来像这样: text 10 30 (它将从 .txt 文件的第 10 行打印到第 30 行)
我设法打印了所有行,但不知道如何在范围内显示它们。我正在分享我的代码,但如果您知道更简单的方法 - 将不胜感激!
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
bool create_file_with_n_lines(string outfile, int n)
{
ofstream of;
int i;
of.open(outfile.c_str());
for(i = 0; i < n; i++){
of << "line " << i << endl;
}
of.close();
return true;
}
bool get_last_n_lines(string infile, int n)
{
ifstream instream;
instream.open(infile.c_str());
vector<string> v;
char line[256];
int i = 0;
if(n < 1){
return false;
}
while(!instream.eof()){
instream.getline(line, 256);
cout << line << endl;
if(i < n){
v.insert(v.end(), line);
}
else{
string str = line;
if(str.size() != 0)
v.at(i%n) = line;
}
i ++;
}
cout << "after processing" << endl;
int j;
i --;
if(i > n){
i = i % n;
for(j = i; j < n; j ++){
cout << v.at(j).c_str() << endl;
}
}
for(j = 0; j < i; j ++){
cout << v.at(j).c_str() << endl;
}
return true;
}
int main(int argc, char* argv[])
{
string strfile = "out.txt";
create_file_with_n_lines(strfile,12);
get_last_n_lines(strfile, 5);
return 0;
}
解决方案
我相信你多虑了。
要从 to 打印行a
(b
从零开始),请跳过a
行,然后打印下一b-a+1
行。
void print_lines(string infile, int from, int to)
{
ifstream instream(infile);
int count = to - from + 1;
std::string line;
while (from-- && std::getline(instream, line))
{
// Intentionally left blank.
}
while (count-- && std::getline(instream, line))
{
std::cout << line << std::endl;
}
}
推荐阅读
- javascript - 如何渲染同一组件的不同布局?
- java - 使用组合时如何从组合类到达主类?
- c# - C#如何压缩大字符串?
- javascript - 如何删除 Discord.js 中特定用户对消息的反应?
- jetbrains-ide - DataGrip - 如何显示表的授权?
- haskell - 恒等函子是什么样子的?
- cakephp - CakePHP 3.x - viewBuilding()->setLayout('blank') 不工作
- r - 在 Rmarkdown 中使用 KableExtra 生成的列标题中添加百分号 (%)
- google-cloud-platform - 是否需要 OAuth 开发人员验证过程已经验证?
- javascript - 点击 v-for Div 获取对象数据