【发布时间】:2020-11-18 05:04:05
【问题描述】:
在以下代码中,我使用 std::getline 从仅包含“12345”的文件中读取,并在尝试将“67890”写入文件后立即读取。除非我首先调用 myfile.clear(),否则此写入将失败。为什么是这样?究竟是什么破?有没有办法在循环中仍然使用 std::getline 但防止在读取最后一行时发生错误?什么是正确的?
#include <fstream>
#include <iostream>
#include <string>
using std::cout;
using std::fstream;
using std::string;
void printStats(fstream&);
int main(int argc, char* argv[])
{
// textfile.txt:
// 1234
fstream myfile("textfile.txt", std::fstream::in | std::fstream::out);
string line;
cout << "\n"
<< "Before reading lines in a loop.\n";
printStats(myfile);
cout << "\n"
<< "Reading lines in the loop.\n";
while (myfile.eof() != true)
{
std::getline(myfile, line); // Last call here causes EOF and FAIL bit to be set
cout << "line=" << line << "\n";
}
cout << "\n"
<< "After reading lines in a loop.\n";
printStats(myfile);
myfile.clear(); // If I comment this out the write below fails
myfile << "67890\n";
myfile.close();
return 0;
}
void printStats(fstream& fileStream)
{
int position = fileStream.tellp();
cout << "position = " << position << "\n";
if (fileStream.eof() == true)
cout << "EOF bit = 1\n";
else
cout << "EOF bit = 0\n";
if (fileStream.fail() == true)
cout << "FAIL bit = 1\n";
else
cout << "FAIL bit = 0\n";
if (fileStream.bad() == true)
cout << "BAD bit = 1\n";
else
cout << "BAD bit = 0\n";
}
以下是 myfile.clear() 被注释掉的执行结果:
user@Ubuntu:~/example/test$ cat textfile.txt ; ./test ; cat textfile.txt
12345
Before reading lines in a loop.
position = 0
EOF bit = 0
FAIL bit = 0
BAD bit = 0
Reading lines in the loop.
line=12345
line=
After reading lines in a loop.
position = -1
EOF bit = 1
FAIL bit = 1
BAD bit = 0
12345
以下是使用代码中包含的 myfile.clear() 执行的结果:
user@Ubuntu:~/example/test$ cat textfile.txt ; ./test ; cat textfile.txt
12345
Before reading lines in a loop.
position = 0
EOF bit = 0
FAIL bit = 0
BAD bit = 0
Reading lines in the loop.
line=12345
line=
After reading lines in a loop.
position = -1
EOF bit = 1
FAIL bit = 1
BAD bit = 0
12345
67890
这是在 Ubuntu Linux 20.04 上使用 g++ 编译的
user@Ubuntu:~/example/test$ /usr/bin/g++ --version
g++ (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
我确实在下面找到了类似的结果,但它没有清楚地解释我的问题的答案。
c++ getline() looping when used in file with a read in int array?
【问题讨论】:
-
好,完整的问题,但是您可以通过查看
clear的文档来了解它的作用,从而节省一些时间。 -
这并没有解决问题,但
while (myfile.eof() != true)通常写成while (!myfile.eof())。但是,如果您真的非常想与显式值进行比较,那么写while (myfile.eof() == false)会更清楚。
标签: c++