C++ f、 getline()迭代器不增加
我不明白为什么我的迭代器没有增加C++ f、 getline()迭代器不增加,c++,C++,我不明白为什么我的迭代器没有增加 #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 >
#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 Akhmetov在评论中所说的那样,你需要阅读并计算完整的行数。如果要每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_newlinesf,g;调用它
请注意,get和put使用未格式化的I/O,而out可以从int main查看示例吗?这可能是由于使用了未初始化的nr,但我不能确定。与您的问题无关,但请阅读您的问题,您是否记得在循环之前将nr初始化为零?不要告诉我们您已初始化它。你每行增加nr一次,但是你希望nr最多可以计数20个字符。代码和您的目标需要协调。谢谢!说到使用char函数,我真的很糟糕。我现在明白我做错了什么,应该做什么了!真的很感激it@BananaAurie我也很感激你的感谢,但请阅读。