marquesm91
marquesm91

Reputation: 555

C++ How to differentiate std::cin to std::ifstream?

I am trying to make a simple comparison to find if istream is a std::cin or std::ifstream.

My pseudocode is something like that:

class myclass
{
public:
    void write(istream& is)
    {
        if(is == cin) // this does not work
        {
            //do something
        }
        else
        {
            //do something else
        }
    }     
};

How can I proceed?

Thank you!

Upvotes: 2

Views: 1938

Answers (2)

cdhowie
cdhowie

Reputation: 169018

Since std::cin is an instance of std::istream, you could compare the addresses of the two objects to see if they are equal:

if (&is == &std::cin)

(Demo)

However I would consider investigating if you can achieve your goal without doing this; switching logic based on the identity of the stream argument is not very clean and may inhibit future development or maintenance of this project.

Upvotes: 3

Nathan Chappell
Nathan Chappell

Reputation: 2436

I'm not sure why you need to check if you have cin or not, but I had the same problem and my reason was: if I have cin, it means I'm in interactive mode, so I should give some useful information to cout. While checking the address of cin with is will probably hopefully always work, I wouldn't really trust it...

Anyways, my solution was to slightly generalize and add an extra parameter with a reasonable default

void f(istream &i, ostream *o = nullptr) {
    if (o) {
        *o << "useful info...";
    }
    i >> important_variable;
}

This gives a slightly more general function, using the "pointer to parameter means optional parameter" idiom. If you need cin for some other reason, then you may also look into specifically which properties of cin you need, and how to determine if your input stream possesses them.

Upvotes: 0

Related Questions