如何使用C 计数文件中的行数
How to count the number of lines in a file using C++?
单击此处以获取文本文件
我在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++;
}
通过这种方式,您避免计算额外的线
相关文章:
- 有充分的理由在h文件中使用include保护而不是cpp文件吗
- 如何在其他文件中使用函数
- 在实现文件中使用头文件的通用 lambda
- 将 getline() 与文件一起使用
- 在头文件和 cpp 文件中使用一次 #pragma 时出现结构重定义错误
- 定义C++新的环境变量并在 bat 文件中使用它
- 如何在另一个 CPP 文件中使用一个 cpp 文件中的函数?
- 在 embarcadero / RAD 工作室中的 .dfm 文件中使用常量
- 声明要在 qml 和 cpp 文件中使用的全局字符串
- 如何在 linux 可执行文件中使用静态库
- 在C++的头文件中使用常量并在程序中询问其地址的任何潜在危险
- 使用 libssh 从 SFTP 服务器下载文件并使用 C++ 将其写入 ofstream?
- CocoaPod - 在头文件中使用 C++ 时出现 Podspec 检查错误
- 链接器输入文件未使用,因为链接未完成,我无法获得.o
- 使用个人C++库编译代码时,与头文件一起使用时会中断
- 如何为文件路径使用变量?
- 没有头文件如何使用c ++调用其他模块中的函数?
- 在带有类型保护的模板文件中使用前向声明
- 无法使包含.hpp文件与其中的2个文件一起使用
- 文件删除(使用取消链接)与释放所有磁盘空间之间的延迟