C++ 使用类来计算文件中的行数

c++ using class to count lines in file

本文关键字:文件 计算 C++      更新时间:2023-10-16

我正在尝试将我的行计数函数移动到一个类中,但是,我遇到了一些错误,我不知道如何使其工作。

    class lines {
        string name;
        int number_of_lines;
        string line;
    public:
        void set_value (string n);
        ifstream myfile(name);   //C2061: syntax error : identifier 'name'
        while (getline(myfile, line))  //Multiple markers at this line - C2059: syntax error : 'while', - Syntax error
        {                         // C2334: unexpected token(s) preceding '{'; skipping apparent function body
            ++number_of_lines;
        }
        int row() {return number_of_lines;}
    };
 void lines::set_value (string n) {
 number_of_lines=0;
     name = n;
 }

我将错误作为注释添加到它们显示的行中。

更改代码

        string line;
public:
        void set_value (string n);
        ifstream myfile(name);   //C2061: syntax error : identifier 'name'
        while (getline(myfile, line))  //Multiple markers at this line - C2059: syntax error : 'while', - Syntax error
        {                         // C2334: unexpected token(s) preceding '{'; skipping apparent function body
            ++number_of_lines;
        }

自:

public:
    void set_value (string name)
    {
        ifstream myfile(name);
        string line;
        while (getline(myfile, line)) 
        {               
            ++number_of_lines;
        }
        myfile.close();
    }
无论您在

必须位于某个函数内部的C++中执行的任何操作/计算,这里您都在必须在某个函数内的类中使用以下语句。

ifstream myfile(name);   //C2061: syntax error : identifier 'name'
        while (getline(myfile, line))  //Multiple markers at this line - C2059: syntax error : 'while', - Syntax error
        {                         // C2334: unexpected token(s) preceding '{'; skipping apparent function body
            ++number_of_lines;
        }