C++ 入门第 5 版第 17.5.3 章 fstream 没有添加新行
C++ primer 5th edition Chapter 17.5.3 fstream doesn't put new line
这是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";
无论如何,它都应该放置一个新的空白行。哪里出了问题?
问题是,通过到达文件末尾,流的坏位被设置了。如果添加
inOut.clear();
在最后一个 inOut <<""之前,换行符按预期写入,尽管没有换行符的行长度仍然不会添加。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 在fstream期间忽略空行
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- C++ 入门第 5 版第 17.5.3 章 fstream 没有添加新行
- Fstream C 自动线添加
- 为 fstream 添加 NULL 终止符
- 为什么'ifstream'和'ofstream'被添加到"std",而'fstream'可以同时达到这两个目的?
- fstream正在为我的文件的每一行添加字符
- 在fstream中添加数字(c++)
- 如何检测新行并将其添加到字符串中.Fstream
- c++ fstream -如何在.open()中添加变量而不是字符串
- 如何在c++中使用fstream在文本文件中添加新文本