【问题标题】:Getting error when counting the number of lines of text in a text file in c++在 C++ 中计算文本文件中的文本行数时出错
【发布时间】:2014-05-11 07:43:02
【问题描述】:

我正在尝试计算文本文件中的行数,但每次运行此代码时,我都会得到 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;
}

【问题讨论】:

  • 首先:正确初始化变量怎么样? int numLine = 0;
  • 大声笑我已经发现了我的错误。没看到那个。还是谢谢你。
  • 回答自己,让所有人都学习
  • 这就是我所做的。谢谢。

标签: c++ string file


【解决方案1】:

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

#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;
}

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 2011-03-29
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    相关资源
    最近更新 更多