该tellg()
函数的工作原理是尝试构造一个哨兵对象,然后failbit
在返回正确的值之前检查 。如果failbit
设置了,则返回 -1。可以在此处找到详细信息,或者,如果您更喜欢更官方的来源并且不介意干读,ISO C++ 标准(27.6.1.3/36a-37
对于 C++03,27.7.2.3/39-40
对于 C++11)。
哨兵的构造首先检查任何错误标志(如eofbit
),如果设置,它设置failbit
并返回。有关详细信息,请参见此处(C++03 27.6.1.1.2
、C++11 27.7.2.1.3
),
因此tellg()
,设置文件结束标志后的 a 将失败。您正在读取行直到getline
返回 false 的事实意味着eofbit
正在设置流,因此您已经到达文件的末尾。
您可以使用以下程序查看行为:
#include <iostream>
#include <iomanip>
int main (void) {
std::string line;
while (std::getline (std::cin, line)) {
if (line.length() > 20)
line = line.substr(0,17) + "...";
std::cout << "tellg() returned "
<< std::setw(5) << std::cin.tellg()
<< " after " << line << "\n";
}
//std::cin.clear();
std::cout << "tellg() returns: "
<< std::cin.tellg() << '\n';
return 0;
}
当您运行它并将文件本身作为输入提供时,您会看到:
tellg() returned 20 after #include <iostream>
tellg() returned 39 after #include <iomanip>
tellg() returned 40 after
tellg() returned 58 after int main (void) {
tellg() returned 80 after std::string l...
tellg() returned 124 after while (std::g...
tellg() returned 156 after if (line....
tellg() returned 202 after line ...
tellg() returned 243 after std::cout...
tellg() returned 291 after << st...
tellg() returned 333 after << " ...
tellg() returned 339 after }
tellg() returned 363 after //std::cin.cl...
tellg() returned 400 after std::cout << ...
tellg() returned 437 after << std::c...
tellg() returned 451 after return 0;
tellg() returned 453 after }
tellg() returned 454 after
tellg() returns: -1
如果您取消注释该代码中清除错误状态变量的行,它将起作用:
tellg() returned 20 after #include <iostream>
tellg() returned 39 after #include <iomanip>
tellg() returned 40 after
tellg() returned 58 after int main (void) {
tellg() returned 80 after std::string l...
tellg() returned 124 after while (std::g...
tellg() returned 156 after if (line....
tellg() returned 202 after line ...
tellg() returned 243 after std::cout...
tellg() returned 291 after << st...
tellg() returned 333 after << " ...
tellg() returned 339 after }
tellg() returned 361 after std::cin.clea...
tellg() returned 398 after std::cout << ...
tellg() returned 435 after << std::c...
tellg() returned 449 after return 0;
tellg() returned 451 after }
tellg() returned 452 after
tellg() returns: 452
而且,顺便说一句,看起来您所指的错误可能是这个错误(这有点不清楚,因为您链接到的帖子遗憾地缺少任何细节 - 如果发帖人费心支持他的断言会更好它是一个已知的错误,例如,链接到它)。
如果是这种情况,您首先应该注意到的是它在十多年前就已修复,因此,除非您使用的是绝对古老 gcc
的 ,否则现在不会成为问题。