C++ 计算文本文件中行数的最佳条件是什么?

C++ 计算文本文件中行数的最佳条件是什么?,c++,C++,我有下面的代码,我试图计算输入文件中的行数,我尝试了几种不同的实现方法,但没有成功 int checkData(string File) { string temp; int linecount = 0; ifstream input(File); input.open(File); while () { getline(input,temp); linecount++; temp.clear(); } return lin

我有下面的代码,我试图计算输入文件中的行数,我尝试了几种不同的实现方法,但没有成功

int checkData(string File)
{
string temp;
int linecount = 0;
ifstream input(File);
input.open(File);

while ()
    {   
        getline(input,temp);
        linecount++;
        temp.clear();
    }
return linecount;
}

到目前为止,我已经尝试:

while(!input.eof())
    {
     ...
    }

第一个没有打破循环,我不太清楚为什么。(我相当肯定)getline有一个内置的流缓冲区,所以每次我拉入一行并将其抛出时,它都应该自动读取网线,但没有骰子。第二,循环根本不执行,这对我来说仍然没有意义(也就是说第一行文件不是很好的输入?)。 我使用的测试文件是:

this is a test     this     Cake
this is a test     this     Cake
this is a test     this     Cake
this is a test     this     Cake
因此,正确执行时,linecount应返回为4。在执行此操作之前,我已经检查了文件是否正确打开

希望能有帮助


希望有帮助。

第一个是众所周知的问题。从第二个删除
.good()
应该可以解决这个问题。只要运行它,在删除.good()标志时它仍然不会执行while循环。@GrahamWilson您应该仔细检查一下——删除good()确实可以解决您的问题(不仅仅是原则上的问题;我复制并编译了您的代码)。顺便说一句,temp.clear()不是必需的。@GrahamWilson.。请参阅关于第一个版本的内容第一个是众所周知的问题。从第二个删除
.good()
应该可以解决这个问题。只要运行它,在删除.good()标志时它仍然不会执行while循环。@GrahamWilson您应该仔细检查一下——删除good()确实可以解决您的问题(不仅仅是原则上的问题;我复制并编译了您的代码)。顺便说一句,temp.clear()不是必需的。@GrahamWilson.。请参阅关于第一个版本的内容
this is a test     this     Cake
this is a test     this     Cake
this is a test     this     Cake
this is a test     this     Cake
int number_of_lines = 0;
string line;
ifstream myfile("textexample.txt");
while (std::getline(myfile, line))
    ++number_of_lines;