2

这是C++ 入门书第 5 版第 17 章 (17.5.3) 的示例代码。

int main(void) {

    fstream inOut("test.txt", fstream::ate | fstream::in | fstream::out);
    if (!inOut)
    {
        cerr << "Unable to open file!" << endl;
        return EXIT_FAILURE;
    }

    auto end_mark = inOut.tellg();
    inOut.seekg(0, fstream::beg);
    size_t cnt = 0;
    string line;

    while (inOut && inOut.tellg() != end_mark && getline(inOut, line))
    {
        cnt += line.size() + 1;
        auto mark = inOut.tellg();
        inOut.seekg(0, fstream::end);
        inOut << cnt;

        if (mark != end_mark)
        {
            inOut << " ";
        }

        inOut.seekg(mark);
    }

    inOut.seekg(0, fstream::end);
    inOut << "\n";
    return 0;
}

该文件的内容test.txt是:

abcd
efg
hi
j
<This is a blank new line>

关键是,如果此文件以空行结尾,则此代码按预期工作。换句话说,它将文件更改为:

abcd
efg
hi
j
5 9 12 14
<This is a blank new line>

但是,如果文件没有以空白新行结尾,它将输出如下:

abcd
efg
hi
j5 9 12 

请注意,此文件不以新行结尾。我的问题是空白的新行在哪里?毕竟有代码

inOut << "\n";

无论如何,它都应该放置一个新的空行。哪里错了?

4

1 回答 1

2

问题是通过到达文件末尾,流的坏位被设置。如果你添加

inOut.clear();

在最后的 inOut << "\n" 之前,换行符按预期写入,尽管没有换行符的行的长度继续不被添加。

于 2017-12-30T20:38:57.677 回答