在c++中计算文本文件中的文本行数时出现错误

Getting error when counting the number of lines of text in a text file in c++

本文关键字:文本 错误 c++ 计算 文件      更新时间:2023-10-16

我试图计算文本文件中的行数,但每次我运行此代码时,我都将1987121509作为行数。你能告诉我如何修改我的代码以获得正确的行数吗?谢谢你。

代码如下:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string line;
int numLine;
ifstream dataFile;
dataFile.open("fileforstring.txt"); 
if(!dataFile)
{
    cout<<"Error opening file.";
}
else
{
    cout<<"File opened successfully";
}
while(getline(dataFile,line))
{
    ++numLine; //increment numLine each time a line is found
}
cout<<"nNo of lines in text file is "<<numLine;
dataFile.close();
return 0;
}

下面是正确的代码(我在问问题后发现)没有正确初始化变量的愚蠢错误。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
string line;
int numLine = 0; //didn't set it to zero.
ifstream dataFile;
dataFile.open("fileforstring.txt");
if(!dataFile)
{
    cout<<"Error opening file.";
}
else
{
    cout<<"File opened successfully";
}
while(getline(dataFile,line))
{
    ++numLine;
}
cout<<"nNo of lines in text file is "<<numLine;
dataFile.close();
return 0;
}