c++ - fstream get(char*, int) 如何操作空行?

标签 c++ get fstream

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/

相关文章:

C++ WinAPI。从文件中读取第一行,显示在文本框中

c++ - 如何根据用户输入打开和读取文件 C++

c++ - vim 在 ifstream 输入期间文件末尾的新行

c++ - 如何评估代码的复杂性 (Big-O)?

c++ - 将值输入到结构

javascript - 无效的主机 header

get - HTTP 服务器 Python : how to test it in local?

c++ - 任何用于 C 或 C++ 的运行时可配置解析器库?

c++ - 在 C++ 中检查 vector 的所有元素是否相等

javascript - 如何在html代码中使用json文件