fstream get(char*, int) how to operate empty line?

2019-07-10 02:36发布

问题:

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;
}

I want to operate all file but in strfile.out:

1: #include <fstream>
2: #include <iostream>
3: #include <assert.h>
4: ...(many empty line)

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()".

回答1:

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.

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();


标签: c++ get fstream