How to use ostream?

Started by
4 comments, last by markspend001 11 years ago

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?

Advertisement

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

It was just an exercise to output text with it.

If you're just outputting text, then you can pass std::cout as an argument to your function. myObject.print(std::cout);

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;

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

This topic is closed to new replies.

Advertisement