代码:
#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();