【问题标题】:C++ primer 5th edition Chapter 17.5.3 fstream doesn't put new lineC++入门第5版第17.5.3章fstream没有换行
【发布时间】:2017-12-30 20:12:39
【问题描述】:

这是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";

在任何情况下都应该添加一个新的空行。哪里错了?

【问题讨论】:

    标签: c++ fstream seekg


    【解决方案1】:

    问题在于,到达文件末尾时,会设置流的坏位。如果你添加

    inOut.clear();
    

    在最后的 inOut

    【讨论】:

    • 经过测试。像魅力一样工作。 :) 我回顾了第 8 章(8.1.2),它确实提到了这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2021-08-25
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多