如何在几个空行后打印文件中的输出
How to print output in a file after a few empty lines
我在这里要做的是打印单词"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(( 似乎不起作用。 有人知道在这里做什么吗?
首先,不要读取和写入同一个文件。文件以不同的模式打开,因此这不起作用。但除此之外,更好的做法是解析您的输入,然后在内存中对其进行操作并写出所需的结果。因此,打开文件,读取感兴趣的内容(您可以存储带有有趣线条的地图,或将整个内容读入内存(,然后对其进行操作,并写出结果。
相关文章:
- 回溯C++不打印函数,因此文件
- 在gem5中打印文件中的所有cache_blocks
- 打印逐行存储的文本文件
- 读取文件中所有可能的十六进制 16 字节序列并打印每个序列
- C/C++:打印(配置)头文件的内容
- 如何使代码打印文本文件中的第一行?
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 按单词搜索文件,然后在C++中打印特定行数
- C++ 尝试优化每一帧将数据打印到二进制文件
- 如何访问头文件中类的组件并打印它们的地址?
- 如何在c ++中以一行(水平)打印两个文件的数据?如给定的.这两种形式来自两个不同的文本文件
- 使用 fstream 库并在屏幕上打印的文件有问题?
- 如何在几个空行后打印文件中的输出
- 二进制文件以及如何对其采取行动(打印文件)
- C 获取目录路径,解析文件夹名称和来自Parent Directory的打印文件内容
- 打印文件中的文本
- 如何打印文件的内容
- 打印文件的分段故障特征
- 打印文件夹中的文件
- 用c++打印文件的第n列