user2031585
user2031585

Reputation: 43

c++ using class to count lines in file

I am trying to move my line counting function into a class, however, I am getting a few errors, and I have no idea how to make it work.

    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;
 }

I added the errors as comments to the rows they show up on.

Upvotes: 1

Views: 137

Answers (2)

herohuyongtao
herohuyongtao

Reputation: 50667

Change code

        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;
        }

to :

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

Upvotes: 1

rajenpandit
rajenpandit

Reputation: 1361

Whatever operation/calculation you are doing in C++ that must be inside some function, here you are using the below statements inside class that must be inside some function.

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;
        }

Upvotes: 0

Related Questions