如何使用标准类 fstream
和 ifstream
计算行数?
如何使用标准类 fstream
和 ifstream
计算行数?
怎么样,试试这个:
std::ifstream inFile("file");
std::count(std::istreambuf_iterator<char>(inFile),
std::istreambuf_iterator<char>(), '\n');
@MIH
:通过快速的谷歌搜索,你会发现std::count()
在 <algorithm>
头文件中。 - James McNellis#include <algorithm>
- Abhaysize_t n = 0; while (getline (stream, string)) n++;
将准确报告行数,无论文件是否具有POSIX eof
。如此回答中所示的std::count
方法将无法计算最后一行--即使存在要读取的文本。行数应该是准确的。整个问题的底层原因是为什么少数文本编辑器继续使用非POSIX结尾来写文件。:)
- David C. Rankin这是正确版本的Craig W. Wright的回答:
int numLines = 0;
ifstream in("file.txt");
std::string unused;
while ( std::getline(in, unused) )
++numLines;
你逐行读取文件。 计算你读取的行数。
遵循@Abhay的核方法
我完成了一个完整的代码:
#include <fstream>
std::size_t count_line(std::istream &is) {
// skip when is not open or got bad
if (!is || is.bad()) { return 0; }
// save state
auto state_backup = is.rdstate();
// clear state
is.clear();
auto pos_backup = is.tellg();
is.seekg(0);
size_t line_cnt;
size_t lf_cnt = std::count(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>(), '\n');
line_cnt = lf_cnt;
// if the file is not end with '\n' , then line_cnt should plus 1
// but we should check whether file empty firstly! or it will raise bug
if (is.tellg() != 0) {
is.unget();
if (is.get() != '\n') { ++line_cnt; }
}
// recover state
is.clear() ; // previous reading may set eofbit
is.seekg(pos_backup);
is.setstate(state_backup);
return line_cnt;
}
它不会改变原始文件流的状态,包括处理最后一行缺失'\n'的情况。
感谢@masoomyf指出我的错误,我太蠢了没想到!
std::ifstream fin{"source.txt"};
std::count(std::istream_iterator<char>(fin >> std::noskipws), {}, '\n');
int aNumOfLines = 0;
ifstream aInputFile(iFileName);
string aLineStr;
while (getline(aInputFile, aLineStr))
{
if (!aLineStr.empty())
aNumOfLines++;
}
return aNumOfLines;
empty()
检查。 - Remy Lebeau
int numLines = 0;
ifstream in("file.txt");
//while ( ! in.eof() )
while ( in.good() )
{
std::string line;
std::getline(in, line);
++numLines;
}
关于文件的最后一行如果没有以换行符结尾应该如何处理,这是一个问题。根据你的需求,你可能想要计算它,也可能不想计算。这段代码会计算它。
while ( ! in.eof() )
这样的语句,如果在读取文件时出现任何故障,它会产生垃圾数据。应该将std::getline
作为while循环的条件。 - Billy ONealstd::getline
失败,会增加行数计数器,并且直到之后才检查是否成功,因此仍然无效。将 std::getline
移到 while 循环的条件中。请注意不要改变原意。 - Billy ONeal将文件大小除以每行平均字符数!