如何计算 C++ 中文件的行数?
如何使用标准类 fstream
和 ifstream
计算行数?
How can I count lines using the standard classes, fstream
and ifstream
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
如何使用标准类 fstream
和 ifstream
计算行数?
How can I count lines using the standard classes, fstream
and ifstream
?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(8)
这个怎么样:-
How about this :-
您逐行读取文件。
计算您阅读的行数。
You read the file line by line.
Count the number of lines you read.
这是 Craig W. Wright 答案的正确版本:
This is the correct version of Craig W. Wright's answer:
之后的内核方法
@Abhay我完成的完整代码
:它不会更改原始文件流状态,并包括最后一行的“\n”缺失情况处理。
感谢 @masoomyf 指出我的错误,我太愚蠢了,无法弄清楚!
kernel methods following @Abhay
A complete code I've done :
it will not change the origin file stream state and including '\n'-miss situation processing for the last line.
Thanks @masoomyf for pointing my bug and I was too stupid to figure it out!
这对我有用:
This works for me:
存在一个问题,如果文件的最后一行不以换行符结尾,如何处理它。根据您在做什么,您可能想计算它,也可能不想计算。这段代码算了。
请参阅:http://www.cplusplus.com/reference/string/getline/
There is a question of how you treat the very last line of the file if it does not end with a newline. Depending upon what you're doing you might want to count it and you might not. This code counts it.
See: http://www.cplusplus.com/reference/string/getline/
将文件大小除以每行的平均字符数!
Divide the file size by the average number of characters per line!