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

早过忘川 提交于 2019-12-24 03:01:17

问题


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


来源:https://stackoverflow.com/questions/11453522/fstream-getchar-int-how-to-operate-empty-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!