相关疑难解决方法(0)

计算文本文件中的行数

我正在阅读文本文件中的行,我想知道这是否是一个好方法?我必须编写函数numberoflines来减少number_of_lines variable一个,因为在while循环中,对于它读取的每一行,它都会向number_of_lines变量添加2.

#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;
}
Run Code Online (Sandbox Code Playgroud)

还有其他更容易更好的方法吗?

c++ text gcc file

24
推荐指数
2
解决办法
17万
查看次数

标签 统计

c++ ×1

file ×1

gcc ×1

text ×1