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 中:
1: #include <fstream>
2: #include <iostream>
3: #include <assert.h>
4: ...(many empty line)
我知道 fstream.getline(char*, int) 这个函数可以管理它,但我想知道如何使用函数“fstream.get()”。
最佳答案
因为 ifstream::get(char*,streamsize)
会将分隔符(在本例中为 \n
)留在流中,您的调用永远不会前进,因此它在您的调用程序看来,您正在无休止地阅读空白行。
相反,您需要确定换行符是否正在等待流,并使用 in.get()
或 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();
关于c++ - fstream get(char*, int) 如何操作空行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11453522/