计算文本文件中的行数 [英] counting the number of lines in a text file
问题描述
我正在阅读文本文件的行,我想知道这是否是一个很好的方法去?我不得不写的函数 numberoflines
减少 number_of_lines变量
一个,因为在while循环中,对于每一行读取它为number_of_lines变量添加2。
I'm reading lines off of text file and I'm wondering if this is a good way to go? I had to write the function numberoflines
to decrease the number_of_lines variable
by one because within the while loop, for every line it read it adds 2 to the number_of_lines variable.
#include <iostream>
#include <fstream>
using namespace std;
int number_of_lines = 0;
void numberoflines();
int main(){
string line;
ifstream myfile("textexample.txt");
if(myfile.is_open()){
while(!myfile.eof()){
getline(myfile,line);
cout<< line << endl;
number_of_lines++;
}
myfile.close();
}
numberoflines();
}
void numberoflines(){
number_of_lines--;
cout<<"number of lines in text file: " << number_of_lines << endl;
}
还有其他更简单的方法吗?
Is there any other easier better way?
推荐答案
你的黑客递减计数到底是什么 - 一个黑客。
Your hack of decrementing the count at the end is exactly that -- a hack.
更好地首先正确编写循环,因此它不会将最后一行计数两次。
Far better to write your loop correctly in the first place, so it doesn't count the last line twice.
int main() {
int number_of_lines = 0;
std::string line;
std::ifstream myfile("textexample.txt");
while (std::getline(myfile, line))
++number_of_lines;
std::cout << "Number of lines in text file: " << number_of_lines;
return 0;
}
个人而言,我认为在这种情况下,C风格的代码是完全可以接受的:
Personally, I think in this case, C-style code is perfectly acceptable:
int main() {
unsigned int number_of_lines = 0;
FILE *infile = fopen("textexample.txt", "r");
int ch;
while (EOF != (ch=getc(infile)))
if ('\n' == ch)
++number_of_lines;
printf("%u\n", number_of_lines);
return 0;
}
编辑:当然,C ++也会让你做一些类似的事情:
Of course, C++ will also let you do something a bit similar:
int main() {
std::ifstream myfile("textexample.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;
}
这篇关于计算文本文件中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!