0

I'm making this class called filestream, it's supposed to spit out a (txt) file like a stream. I'm done but the thing is that the last entry is given twice. What am I doing wrong here?

filestream.h:

class filestream {

public:
    std::string file_location;
    std::string get();
    explicit filestream(std::string file_location);
    bool at_end();
private:
    std::stringstream ss;
    std::string s;
    std::fstream f;

};

filestream.cpp:

filestream::filestream(std::string file_location) : file_location(file_location) {
    f.open(file_location);
}

std::string filestream::get() {
    if (f.is_open()) {
        f >> s;
        return s;
    } else {
        return nullptr;
    }
}

bool filestream::at_end() {
    return f.eof();
}

test.cpp:

#include "demonic.h"

int main (){

    filestream fs("/home/devilish/Desktop/fruit.txt");
    while (!fs.at_end()){
        std::cout << fs.get() << std::endl;
    }
    return 0;
}

output:

Apple
Peer
Cherry
Mango
Mango

I tried this class twice but the results are the same, can anyone help me with this?

  • 2
    I would say the single commonest misunderstanding we get here. `eof()` doesn't do what you think it does. Specifically it doesn't test if you are at the end of the file. Read the duplicate carefully. – john Jul 07 '20 at 18:44
  • 2
    PS `return nullptr;` is incorrect. It's not legal to initialise a `std::string` with `nullptr`, this is likely to crash your program. – john Jul 07 '20 at 18:48
  • In addition, end of file is only one of many things that can go wrong when reading from a stream.. To be completely safe you should check ALL of them, and checking the stream state will report everything except validity of the actual data (if the data is garbage, you're gonna read garbage) . – user4581301 Jul 07 '20 at 18:48
  • Oke, I did not know that, so next question. How am I supposed to do it then? – Demonic-Coder Jul 07 '20 at 18:54
  • I seem to have inadvertently given the C answer as the duplicate. I'll reopen and reclose with the C++ version. – john Jul 07 '20 at 18:55
  • @Demonic-Coder You'll have to reorganise your class, but `while (f >> s) { ... }` is the usual way. – john Jul 07 '20 at 18:56
  • This is the correct duplicate https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons Seems I'm no longer able to close having done it once already. – john Jul 07 '20 at 18:57
  • Thanks but, what about my at_end function now? How am I solving that? – Demonic-Coder Jul 07 '20 at 19:09
  • Why do you need this function? You should check if the read was successful after you read from the file. – Thomas Sablik Jul 07 '20 at 19:21
  • I'll think of something but thanks, I learned today. – Demonic-Coder Jul 07 '20 at 19:23

0 Answers0