我试图计算文本文件中的行数,但是每次我运行此代码时,我都会得到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;
}
关于c++ - 在C++中计算文本文件中的文本行数时出现错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23590197/