我正在通过这样的函数读取文件:

#include <iostream>
#include <fstream>
#include <string>
...
void readfile(string name){

    string line;
    int p = 0;
    ifstream f(name.c_str());

    while(getline(f,line)){
        p++;
    }
    f.seekg(0);
    cout << p << endl;

    getline(f,line);
    cout << line << endl;
}


Mi文件有3行:

first
second
third


我期望输出:

3
first


相反,我得到:

3
(nothing)


为什么我的搜索不起作用?

最佳答案

因为如果流到达文件末尾(设置了seekg()),eofbit就会失败,这是由于您的getline循环而发生的。就像sftrabbit所暗示的那样,调用clear()将重置该位,并且应该可以使您正常查找。 (或者您可以只使用C ++ 11,其中seekg会清除eofbit本身。)

10-06 15:38