有没有我可以用来获取总文件行号的函数C++
,还是必须通过for
循环手动完成?
#include <iostream>
#include <ifstream>
ifstream aFile ("text.txt");
if (aFile.good()) {
//how do i get total file line number?
}
文本.txt
line1
line2
line3
我会这样做:
ifstream aFile ("text.txt");
std::size_t lines_count =0;
std::string line;
while (std::getline(aFile , line))
++lines_count;
或者简单地说,
#include<algorithm>
#include<iterator>
//...
lines_count=std::count(std::istreambuf_iterator<char>(aFile),
std::istreambuf_iterator<char>(), '\n');
没有这样的功能。计数可以通过读取整行来完成
std::ifstream f("text.txt");
std::string line;
long i;
for (i = 0; std::getline(f, line); ++i)
;
关于范围的注释,如果你想在循环之后访问它,变量i
必须在外部。for
您也可以按字符阅读并检查换行符
std::ifstream f("text.txt");
char c;
long i = 0;
while (f.get(c))
if (c == '\n')
++i;
我担心您需要像这样自己编写它:
int number_of_lines = 0;
std::string line;
while (std::getline(myfile, line))
++number_of_lines;
std::cout << "Number of lines in text file: " << number_of_lines;
有一个计数器,初始化为零。逐行读取,同时增加计数器(该行的实际内容不感兴趣,可以丢弃)。完成后,没有错误,计数器就是行数。
或者您可以将所有文件读入内存,并计算大块文本“数据”中的换行符。
https://stackoverflow.com/a/19140230/9564035中的解决方案很好,但不能提供相同的输出。如果您想计算仅以'\n'
use结尾的行
#include<algorithm>
#include<iterator>
//...
ifstream aFile ("text.txt");
lines_count=std::count(std::istreambuf_iterator<char>(File),
std::istreambuf_iterator<char>(), '\n');
如果您还想计算未以'\n'
(最后一行)结尾的行,则应使用 getLine 解决方案
ifstream aFile ("text.txt");
std::size_t lines_count =0;
std::string line;
while (std::getline(aFile , line))
++lines_count;
请注意,如果您之前从文件中读取,则应将指针设置为指向文件开头file.seekg(std::ios_base::beg);
比 P0W 等解决方案更快的方法每 100mb 节省 3-4 秒
std::ifstream myfile("example.txt");
// new lines will be skipped unless we stop it from happening:
myfile.unsetf(std::ios_base::skipws);
// count the newlines with an algorithm specialized for counting:
unsigned line_count = std::count(
std::istream_iterator<char>(myfile),
std::istream_iterator<char>(),
'\n');
std::cout << "Lines: " << line_count << "\n";
return 0;
只需复制并运行。
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
int main()
{
fstream file;
string filename = "sample input.txt";
file.open(filename.c_str()); //read file as string
int lineNum = 0;
string s;
if (file.is_open())
{
while (file.good())
{
getline(file, s);
lineNum++;
cout << "The length of line number " << lineNum << " is: " << s.length() << endl;
}
cout << "Total Line : " << lineNum << endl;
file.close();
}
return 0;
}