passing an ofstream by reference

This is a discussion on passing an ofstream by reference within the C++ Programming forums, part of the General Programming Boards category; This may be a silly question, but here goes. Is there any way I can pass cout as a parameter(by ...

  1. #1
    Registered User
    Join Date
    Aug 2004
    Posts
    45

    passing an ofstream by reference

    This may be a silly question, but here goes. Is there any way I can pass cout as a parameter(by reference of course) into a function that takes an ofstream& as opposed to an ostream&? Basically I have a function that gets an ofstream& as a parameter so that it can continue writing to a pre-defined and pre-opened file. However, I just found the need to also have that function print to the screen. I could make a new function, but it is a fair amount of code and it would be identical. Any ideas?

    Would it be a problem to always pass both?

    Code:
    void function(ostream &sout, ofstream &fout);
    Another question is what is the point of having cin.ignore() after each cin statement. I saw that somewhere and thought I should know.

    One more about classes. Is it necessary to always have a destructor, or do the objects get destroyed anyway after going out of scope?

    Thanks for the help

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,717
    Basically I have a function that gets an ofstream& as a parameter so that it can continue writing to a pre-defined and pre-opened file. However, I just found the need to also have that function print to the screen.
    Chances are you can just write for ostream, and then pass the ofstream object.
    e.g.
    Code:
    std::ostream& writeMe(std::ostream& os, int me) {
    	return os << me;
    }
    int main() {
    	//...
    	int num = 1;
    	std::ofstream out(filename);
    	writeMe(out, num);
    	writeMe(std::cout, num);
    	//...
    }
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. Passing structure by reference or pointer?
    By 7force in forum C Programming
    Replies: 8
    Last Post: 12-13-2010, 05:49 PM
  3. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  4. Question about OpenGL/Linux
    By Ideswa in forum Linux Programming
    Replies: 12
    Last Post: 09-10-2006, 05:56 AM
  5. GCC - Strange networking functions error.
    By maththeorylvr in forum Windows Programming
    Replies: 3
    Last Post: 04-05-2005, 12:00 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21