Search code examples
c++istreamostream

How to determine if the cin is keyboard or from file


I have an input function I'm writing:

void input(istream& ins)

As well as output function:

void output(ostream& outs)

My question is inside of these two functions, I want an if statement that determines if I'm writing from file or writing from keyboard. This is because inside of my input I am using the input to also cout statements if the data is not coming from a file.

I want my output file to determine if its writing to file, or its writing to the screen. Basically, I just want to know how to check for writing from/to file if I want to pass the streams into the functions.


Solution

  • You can do a simple address compare:

    if(&ins == &cin){
    //then you using cin, since there is only one cin object
    }else{
    //other istream
    }
    

    same for cout...

    if(&outs == &cout || &outs == &cerr){
    //then you using standard outputs: cout or cerr
    }else{
    //other ostream
    }