【发布时间】: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";
在任何情况下都应该添加一个新的空行。哪里错了?
【问题讨论】: