Sign in to follow this  
noatom

How to use ostream?

Recommended Posts

noatom    927

I need to solve an exercise,I already created the required member function:

 

void print(ostream& e){
   e << this->i << endl;

}

 

 

But when I want to call that function,I have no ideea how to create that ostream.I never really worked with anything else than cin,cout,get.Little help?

Edited by noatom

Share this post


Link to post
Share on other sites
BitMaster    8651
#include <fstream>

//...
std::ofstream myFile("C:\\mydirectory\\myfile.txt");
//...
myObject.print(myFile);
C:\mydirectory must obviously exist and you must have write permissions there.

The key question is what do you want the stream to do? Apart from std::cout, std::cerr and file streams there are not really many streams around a beginner needs. What do you want?

Share this post


Link to post
Share on other sites
SiCrane    11839
If you're just outputting text, then you can pass std::cout as an argument to your function. [tt]myObject.print(std::cout);[/tt]

Share this post


Link to post
Share on other sites
Muzzy A    737

that's an odd way to print something....

 

you could do it simpler without passing ostream as an arg

 

void Print(const char *str)
{
    std::cout << str;
}

 

and another way of doing it

 

// Friend the function with the class
friend ostream& operator <<( ostream &os,const ClassObj &obj )
{
    os << obj.i;
 
    // Return the ostream for daisy chaining
    return os;
}
 
// Now use it like this
ClassObj obj;
std::cout << obj;
 
// and daisy chain
std::cout << obj << endl << obj << obj;

Share this post


Link to post
Share on other sites
markspend001    100

Hey Guys according to that topic i find the coding related to that topic like:

 

#ifndef SET_
#define SET_

typedef int EType;

using namespace std;

#include <iostream>

class Set
{
private:

struct Node
{
EType Item; // User data item
Node * Succ; // Link to the node's successor
};

unsigned Num; // Number of user data items in the set
Node * Head; // Link to the head of the chain

public:

// Various functions performed on the set

// Display the contents of the set
//
void display( ostream& ) const;

};

#endif

Edited by markspend001

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this