如何在几个空行后打印文件中的输出

How to print output in a file after a few empty lines

本文关键字:打印 文件 输出 几个      更新时间:2023-10-16

我在这里要做的是打印单词"hello",首先在开头,然后跳过几行,然后在文件中再次打印。我需要跳过的行数由用户指定。该文件可能为空,也可能不为空,如果它不为空,则我不想更改需要打印以外的行上的数据。如果文件为空,则它必须跳过空行并在几行后仍打印。

这是我的代码:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main(){
ifstream f1("temp.txt");
ofstream f2("temp.txt");
int r;
cout << "Enter number of lines to skip:" ;
cin >> r;
f2 << "hello";
string org = "";
while(--r){
getline(f1, org);
cout << "org: "<< endl;
}
int pos = f1.tellg();
cout << "pos: " << pos << endl;
f2.seekp(pos, f2.beg);
f2 << "hello";
}

例如,当我输入 r=3 并且文件为空时,我收到的输出:

org: 
org: 
pos: -1

此外,该文件仍为空。无输出。 tellg(( 似乎不起作用。 有人知道在这里做什么吗?

首先,不要读取和写入同一个文件。文件以不同的模式打开,因此这不起作用。但除此之外,更好的做法是解析您的输入,然后在内存中对其进行操作并写出所需的结果。因此,打开文件,读取感兴趣的内容(您可以存储带有有趣线条的地图,或将整个内容读入内存(,然后对其进行操作,并写出结果。