Parametrized stream manipulator

R

rwawryk

Hi,

Does anybody know how to implement parametrized stream operator (such as
setw, setfill)? I need to put into the stream variable of type char* without
terminating NULL. It would be great if I had the manipulator which allows to
determine maximum number of characters ( let's assume maxw( char* str, int
maxlen ) ).

example:
cout << maxw("Crocodile", 5 );
Croco

thanx in advance
ralfer

ps. prefer templates to macros... :)
 
V

Victor Bazarov

rwawryk said:
Does anybody know how to implement parametrized stream operator (such as
setw, setfill)? I need to put into the stream variable of type char* without
terminating NULL. It would be great if I had the manipulator which allows to
determine maximum number of characters ( let's assume maxw( char* str, int
maxlen ) ).

example:
cout << maxw("Crocodile", 5 );
Croco

thanx in advance
ralfer

ps. prefer templates to macros... :)

(a) If you need to put several chars into the stream, just put
them into the stream. No "terminating NULL" is copied into the
stream. cout << string("Crocodile").substr(5); should do it.

(b) Usually parameterised manipulators are written either as
functions that return special objects or just as classes [that
you construct right there], which, when output to a stream, do
something to the stream:

struct maxw {
maxw(const char*, int); // constructor
ostream& print(ostream&) const; // output
// some data
};

ostream& operator <<(ostream& os, const maxw& m) {
return m.print(os);
}

maxw::maxw(const char* s, int n) : ....

ostream& maxw::print(ostream& os) const {
// do something to the stream to output what you need
// in a special way
}

HTH

Victor
 
S

Shane Beasley

Victor Bazarov said:
(a) If you need to put several chars into the stream, just put
them into the stream. No "terminating NULL" is copied into the
stream. cout << string("Crocodile").substr(5); should do it.

That's "odile". You meant string("Crocodile").substr(0, 5). :)

- Shane
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top