Bledson
Bledson

Reputation: 403

Using getline with ifstream class member

The compiler error is:

no matching function for call to 'getline(const ifstream&, std::string&)'

StartScreen.h

#include <fstream>
#include <string>
#include "Screen.h"

class StartScreen: public Screen {
public:
    StartScreen();
    virtual ~StartScreen();
    void advise() const;
    void draw() const;
private:
    StartScreen(const StartScreen&) = delete;
    StartScreen& operator=(const StartScreen&) = delete;
    std::ifstream screen_content_;
};

StartScreen.cpp

#include "StartScreen.h"

StartScreen::StartScreen() {
    screen_content_.open("start-screen.txt");
}

StartScreen::~StartScreen() {
    screen_content_.close();
}

void StartScreen::advise() const {
}

void StartScreen::draw() const {
    std::string line;
    if (screen_content_.is_open()) {
        while (screen_content_.eof()) {
            std::getline(screen_content_, line);
        }
    }
}

My idea is to print all lines from a text file in standard output. Using fstream is the right way? Or there's a better solution?

Upvotes: 0

Views: 249

Answers (1)

Jonathan Wakely
Jonathan Wakely

Reputation: 171413

As the comment above says, the problem that draw() is declared const.

In a const member function all your member variables are treated as const.

Reading from a stream alters the stream object (it has to fill the stream buffer and update the stream position) so you can't do it on a const stream.

Either make draw() non-const, or make screen_content_ mutable.

Upvotes: 3

Related Questions