如何使用C ++计算文件中的行数?

时间:2017-03-03 05:47:06

标签: c++

click here for the text file

我在Code :: Blocks IDE中使用了以下代码。我得到的行数为2.请帮助我使用代码。

#include <iostream>
#include <fstream>
#include <string>

using namespace std;


int main()
{
ifstream in("readInt.txt", ios::in);
if(!in)
{
    cout << "Cannot open file";
    return 1;
}

string str;
int j=0;

while(in)
{
    getline(in,str);
    j++;
}

cout << "No of lines are: " << j;
in.close();
return 0;

}

2 个答案:

答案 0 :(得分:2)

结果太小,因为文本文件中的行结尾的编码方式与系统上的约定不同。

使用正确的系统行结尾保存或重新创建文件。

在另一个方向,对于过高的结果,所呈现的代码

while(in)
{
    getline(in,str);
    j++;
}

...会为空文件生成1的计数。

取而代之的是

while( getline(in,str) )
{
    j++;
}

注意:此评论仅涵盖正确性,而非效率。

答案 1 :(得分:2)

首先,您的文本文件没有新字符,所以在文本中只有一行

更改它并使用

尝试使用代码
while(getline(in,str))
{
    j++;
}
以这种方式你可以避免计算额外的行

相关问题