Thread: problems with passing ostream variable

  1. #1
    Registered User
    Join Date
    Jul 2004
    Posts
    91

    problems with passing ostream variable

    Code:
     string str;
    
                    x.read(inFile);
                    if (x.animalType()==2 || x.animalType()==3)
                            str = std::cerr;
    
                    x.print(str.c_str()) << endl;
    and hte function is...
    Code:
    ostream& animals::print(ostream& stream = cout) const {

    what im trying to do is, read from a file, and if its a dog or a cat, then it'll print out to the error stream.
    and if its any other animal then it'll print out to standard output (cout)

    any help why this code wont work?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Didn't we just do this in another thread?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User jlou's Avatar
    Join Date
    Jul 2003
    Posts
    1,090
    Your variable str is a string, but then you try to assign the cerr stream to it. That won't work. Normally, you might have a variable and assign cout or cerr to it as appropriate. In this case, that variable would have to be a reference to ostream, so it is a little more sloppy because you cannot assign to a reference, only initialize it with something. I would suggest something like this:
    Code:
    if (x.animalType()==2 || x.animalType()==3)
        x.print(std::cerr) << endl;
    else
        x.print(std::cout) << endl;
    or this:
    Code:
    ostream& stream = (x.animalType()==2 || x.animalType()==3) ? std::cerr : std::cout;
    x.print(stream) << endl;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need some help...
    By darkconvoy in forum C Programming
    Replies: 32
    Last Post: 04-29-2008, 03:33 PM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Need help passing a variable between forms
    By GUIPenguin in forum C# Programming
    Replies: 8
    Last Post: 07-10-2006, 03:13 AM
  4. variable passing problem
    By bsimbeck in forum C Programming
    Replies: 3
    Last Post: 02-09-2003, 06:43 PM
  5. Variable Allocation in a simple operating system
    By awkeller in forum C Programming
    Replies: 1
    Last Post: 12-08-2001, 02:26 PM