f.getline() 迭代器不增加
f.getline() iterator not increasing
我不明白为什么我的迭代器(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 上运行)。
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- f.getline() 迭代器不增加
- 使用迭代器增加
- 减少 begin() 迭代器,然后再次增加它
- 增加迭代器标准映射
- 为什么 QVector 的迭代器使用前缀增加,而后缀在内部减少?
- C++映射/设置迭代器在使用多映射时出现不可增加的错误
- 为什么我们在这里增加 ostream 迭代器
- 为什么迭代器在与map.begin()一起使用时预先增加了
- 如何使用擦除-删除习惯用法并在循环中增加迭代器
- 为什么std::copy_n没有将Input迭代器增加n次
- 在将其用作参数时,在内部增加迭代器是否安全