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

How to count the number of lines in a file using C++?

本文关键字:文件 何使用      更新时间:2023-10-16

单击此处以获取文本文件

我在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;
}

您的结果太小了,因为文本文件中的线结尾与系统上的约定不同。

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


在另一个方向上,朝着太高的结果,提出的代码

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

&hellip;对于一个空文件,将产生1个计数。

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

注意:此备注仅涵盖正确性,而不是效率。

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

更改它,并使用

在代码中尝试
while(getline(in,str))
{
    j++;
}

通过这种方式,您避免计算额外的线