Home > Software design >  How to print in a file and with cout with same function in c ?
How to print in a file and with cout with same function in c ?

Time:10-02

I have a simple print function like this:

template <class T>
void ArrayList<T>::print() const {
    //store array contents to text file
    for (int i = 0; i < length; i  )
    {
    cout << *(list   i) << endl;
    }
}

It prints the value in the array. I want it to work like this: If the ArrayList ‘print’ function is called with no argument then it will write the information to the standard output stream. However, a variable of type ‘ofstream’ is then it should write the information to a file.

I changed the function to write in a file but now if I don't pass the argument then it shows an error. Is there a way to make it both write in a file (if the argument passed) and standard print (if no argument)?

template <class T>
void ArrayList<T>::print(std::ofstream& os) const {
    //store array contents to text file
    for (int i = 0; i < length; i  )
    {
    os << *(list   i) << endl;
    }
}

CodePudding user response:

What you can do here is take an std::ostream& as your parameter. Then the print function doesn't care where the data is getting output to.

static void print( std::ostream& os ) 
{
    os << "I don't care where this data is going\n";
}

int main( ) 
{
    // Pass it std::cout.
    print( std::cout );
    
    // Or pass it an std::fstream.
    std::fstream file{ "/Path/To/File/File.txt", std::ios::out };
    print( file );
}
  • Related