• Advertisement
Sign in to follow this  

Simple ifstream question

This topic is 4950 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have this very simple problem and it drives me insane. I think I've missed something in c++... I have this:
#ifndef SCRIPT_H
#define SCRIPT_H

#include <fstream>

class Script
{
private:
    std::ifstream in_;

protected:   
    std::string cachedMessage_;
    unsigned int currentLine_;
    
public:
    Script(void);   
    virtual ~Script(void);

    unsigned int getCurrentLine() { return currentLine_; }
    

    bool open(std::string inFile);
    std::string nextMessage();
};

#endif

and in c++
bool Script::open(std::string inFile)
{        
    in_.open(inFile.c_str()); //Crash!          
    return in_.is_open();
}

Now, the program crashes when in_.open() is called. It gives me an access violation. Why? If I make in_ local then it doesn't crash.

Share this post


Link to post
Share on other sites
Advertisement
You're not accidentaly doing something like this:

Script* s = 0;
.....
s->open("script.file");

Are you? It's happened to me before, quite annoying. Try breaking in Script::open and check that the this pointer is not null and is valid.

- Pete

Share this post


Link to post
Share on other sites
Pete_, yep, thanks, that's the problem...
I got tricked by the compiler since I had an other version of the open function that I could step through without any errors. But that one didn't access any members.

I almost did the same mistake just the other day but I found the problem right away then. Guess I'm tired...

thanks.

Share this post


Link to post
Share on other sites
Just as a note, __fold, you should be passing a const reference to that string, and not a string object. Passing the string object results in unnesessary copying.

Share this post


Link to post
Share on other sites
Washu: Yes, I know, I changed some stuff when it didn't work...

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement