fstream get(char *,int)如何操作空行? [英] fstream get(char*, int) how to operate empty line?
问题描述
strfile.cpp中的代码:
code in strfile.cpp:
#include <fstream>
#include <iostream>
#include <assert.h>
#define SZ 100
using namespace std;
int main(){
char buf[SZ];
{
ifstream in("strfile.cpp");
assert(in);
ofstream out("strfile.out");
assert(out);
int i = 1;
while(!in.eof()){
if(in.get(buf, SZ))
int a = in.get();
else{
cout << buf << endl;
out << i++ << ": " << buf << endl;
continue;
}
cout << buf << endl;
out << i++ << ": " << buf << endl;
}
}
return 0;
}
我要操作所有文件 但在strfile.out中:
I want to operate all file but in strfile.out:
1: #include <fstream>
2: #include <iostream>
3: #include <assert.h>
4: ...(many empty line)
我知道fstream.getline(char *,int)这个函数可以管理它,但是我想知道如何做到这一点,只需使用函数"fstream.get()"即可.
I know that fstream.getline(char*, int) this function can manage it,but I want to know how to do this just use the function "fstream.get()".
推荐答案
由于ifstream::get(char*,streamsize)
将在流上保留定界符(在本例中为\n
),因此您的调用永不进行,因此在您的调用程序中似乎您正在无休止地阅读空白行.
Because ifstream::get(char*,streamsize)
will leave the delimiter (in this case \n
) on the stream, your call never advances and thus it appears to your calling program that you are endlessly reading blank lines.
相反,您需要确定是否有换行符在流上等待,然后使用in.get()
或in.ignore(1)
:
Instead you need to determine if a newline is waiting on the stream, and move past it using in.get()
or in.ignore(1)
:
ifstream in("strfile.cpp");
ofstream out("strfile.out");
int i = 1;
out << i << ": ";
while (in.good()) {
if (in.peek() == '\n') {
// in.get(buf, SZ) won't read newlines
in.get();
out << endl << i++ << ": ";
} else {
in.get(buf, SZ);
out << buf; // we only output the buffer contents, no newline
}
}
// output the hanging \n
out << endl;
in.close();
out.close();
这篇关于fstream get(char *,int)如何操作空行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!