f.getline() 迭代器不增加

f.getline() iterator not increasing

本文关键字:增加 迭代器 getline      更新时间:2023-10-16

我不明白为什么我的迭代器(nr)没有增加。

#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
using namespace std;
ifstream f("date.in");
ofstream g("date.out");
int main()
{
int l, nr = 0;
char  x, s[100];
f >> l;
while(!f.eof())
{
f.getline(s, 100);
{
g << s;
nr++;
}
if(nr == 19)
{
g << 'n';
nr = 0;
}
}
return 0;
}

我希望输出每 20 个字符在新行开始。

问题是你阅读并计算了完整的行@Andrey正如艾哈迈托夫在评论中所说。如果要每 20 个字符注入一个n,最简单的方法是一次读取一个字符:

void add_newlines(std::istream& in, std::ostream& out) {
char ch;
int nr = 0;
// Read one char with "<istream>.get()". The returned file descriptor (in) will
// be true or false in a boolean context (the while(<condition>)) depending on
// the state of the stream. If it fails extracting a character, the failbit will
// be set on the stream and "in" will be "false" in the boolean context and
// the while loop will end.
while( in.get((ch)) ) {
out.put(ch);
if(++nr == 19) {
out << 'n';
nr = 0;
}
}
}

add_newlines(f, g);称呼它.

请注意,get()put()使用未格式化的 I/O,而out << 'n'使用格式化的输出,并且widen()n在 Windows 上rn,这可能会导致输出中出现rrnn等序列(如果在 Windows 上运行)。