Sign in to follow this  

How to use ostream?

This topic is 1703 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
#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
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

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

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

This topic is 1703 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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