473,406 Members | 2,345 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

std::ostream manipulator

Is it possible to manipulate the std::ostream to prepend a string when
performing output, e.g.

// manipute std::cout to prepend "prefix "
std::cout << "hallo" << std::endl;
// results in "prefix hallo"

I need this to overwrite the "<<" operator for MyClass in a recursive
way, e.g.

std::ostream&
operator<<( std::ostream& stream, MyClass const& myClass )
{
// do some output
// prepend '\t' to stream, how?
stream << myClass.member_ << '\n'; // recursive call of << operator
// remove prefix '\t' from stream
return stream;
}

when MyClass has a pointer to another MyClass as a member
(MyClass const* member_). I like to prepend tabs when streaming the
members without saving the prefixes in MyClass.

Thanks,

Boris
Jul 19 '05 #1
8 10342


Boris wrote:
Is it possible to manipulate the std::ostream to prepend a string when
performing output, e.g.

// manipute std::cout to prepend "prefix "
std::cout << "hallo" << std::endl;
// results in "prefix hallo"

I need this to overwrite the "<<" operator for MyClass in a recursive
way, e.g.

std::ostream&
operator<<( std::ostream& stream, MyClass const& myClass )
{
// do some output
// prepend '\t' to stream, how?
stream << myClass.member_ << '\n'; // recursive call of << operator
// remove prefix '\t' from stream
return stream;
}
do you mean simply:
strstream s;
s << "prepended:" << myClass.member_;
stream << s;
-..
or maybe stream << s.str(),

????
/B


when MyClass has a pointer to another MyClass as a member
(MyClass const* member_). I like to prepend tabs when streaming the
members without saving the prefixes in MyClass.

Thanks,

Boris


Jul 19 '05 #2
On 15 Oct 2003 01:49:54 -0700, go***@nexgo.de (Boris) wrote:
Is it possible to manipulate the std::ostream to prepend a string when
performing output, e.g.

// manipute std::cout to prepend "prefix "
std::cout << "hallo" << std::endl;
// results in "prefix hallo"

I need this to overwrite the "<<" operator for MyClass in a recursive
way, e.g.

std::ostream&
operator<<( std::ostream& stream, MyClass const& myClass )
{
// do some output
// prepend '\t' to stream, how?
stream << myClass.member_ << '\n'; // recursive call of << operator
// remove prefix '\t' from stream
return stream;
}

when MyClass has a pointer to another MyClass as a member
(MyClass const* member_). I like to prepend tabs when streaming the
members without saving the prefixes in MyClass.


It's unclear from this whether you need a prefix for each line or
something else. For the former you need the prefix_buf. See the prefix
stuff under IOStreams here:
http://www.informatik.uni-konstanz.de/~kuehl/

Tom
Jul 19 '05 #3
Bob Smith <bo******@jippii.fi> wrote in message news:<3F**************@jippii.fi>...

do you mean simply:
strstream s;
s << "prepended:" << myClass.member_;
stream << s;
-..
or maybe stream << s.str(),


Hi,
streaming MyClass is a multiline message, I need the prefix for each line.
Your solution prepends only a prefix for the first line.

Thanks,
Boris
Jul 19 '05 #4
On 15 Oct 2003 09:00:51 -0700, go***@nexgo.de (Boris) wrote:
Bob Smith <bo******@jippii.fi> wrote in message news:<3F**************@jippii.fi>...

do you mean simply:
strstream s;
s << "prepended:" << myClass.member_;
stream << s;
-..
or maybe stream << s.str(),


Hi,
streaming MyClass is a multiline message, I need the prefix for each line.
Your solution prepends only a prefix for the first line.


In that case, the prefix stream at this site does *exactly* what you
want. There's no other good way to do it within the iostreams
heirarchy.
http://www.informatik.uni-konstanz.de/~kuehl/

Tom
Jul 19 '05 #5
On 15 Oct 2003 01:49:54 -0700, Boris <go***@nexgo.de> wrote:
Is it possible to manipulate the std::ostream to prepend a string when
performing output, e.g.

// manipute std::cout to prepend "prefix "
std::cout << "hallo" << std::endl;
// results in "prefix hallo"

I need this to overwrite the "<<" operator for MyClass in a recursive
way, e.g.

std::ostream& operator<<( std::ostream& stream, MyClass const& myClass )
{
// do some output
// prepend '\t' to stream, how?
stream << myClass.member_ << '\n'; // recursive call of << operator
// remove prefix '\t' from stream return stream;
}

when MyClass has a pointer to another MyClass as a member
(MyClass const* member_). I like to prepend tabs when streaming the
members without saving the prefixes in MyClass.

Thanks,

Boris


I am not sure what you are trying to do here.
If you want a table like output ( tab may do it ) then you just have to
set the
width of next output field by calling,
os.width(...) or os << setw(...)

If you want the tabs to accumulate then you should create an object that
would accumulate the tabs with the << operator to send it to ostream.
Inserting such code to the ostream class seems unnecessery.

--
grzegorz
Jul 19 '05 #6
Hi,
thanks for your answer.

I am not sure what you are trying to do here.
If you want a table like output ( tab may do it ) then you just have to
set the
width of next output field by calling,
os.width(...) or os << setw(...)

I like to do proper indentation for multiline output of
nested data structures.
If you want the tabs to accumulate then you should create an object that
would accumulate the tabs with the << operator to send it to ostream.
Maybe you are right, that seams to be the simplest solution.
Inserting such code to the ostream class seems unnecessery.


Do you think so? You can do nice formating of floating point numbers
with
std::cout << std::scientific for example. Now the formating behaviour
of the stream changes for all succeeding floating point output. I
would appreciate a similar mechanism for strings and prefixes.

Regards,
Boris
Jul 19 '05 #7
tom_usenet <to********@hotmail.com> wrote in message news:<m8********************************@4ax.com>. ..
On 15 Oct 2003 09:00:51 -0700, go***@nexgo.de (Boris) wrote:
Bob Smith <bo******@jippii.fi> wrote in message news:<3F**************@jippii.fi>...

do you mean simply:
strstream s;
s << "prepended:" << myClass.member_;
stream << s;
-..
or maybe stream << s.str(),


Hi,
streaming MyClass is a multiline message, I need the prefix for each line.
Your solution prepends only a prefix for the first line.


In that case, the prefix stream at this site does *exactly* what you
want. There's no other good way to do it within the iostreams
heirarchy.
http://www.informatik.uni-konstanz.de/~kuehl/

Tom


Hi,
I visited the page, thanks for the hint. You are right, this is exactly
what I need, even thought its a much more complicate solution than I hoped
to find. Unfortunatly the cited code does not compile on my platform
(Visual C++ .Net 2003), but I try to contact Dietmar Kuehl for a workaround.

Regards,
Boris
Jul 19 '05 #8
On 16 Oct 2003 07:16:23 -0700, go***@nexgo.de (Boris) wrote:
tom_usenet <to********@hotmail.com> wrote in message news:<m8********************************@4ax.com>. ..
On 15 Oct 2003 09:00:51 -0700, go***@nexgo.de (Boris) wrote:
>Bob Smith <bo******@jippii.fi> wrote in message news:<3F**************@jippii.fi>...
>>
>> do you mean simply:
>> strstream s;
>> s << "prepended:" << myClass.member_;
>> stream << s;
>> -..
>> or maybe stream << s.str(),
>>
>
>Hi,
>streaming MyClass is a multiline message, I need the prefix for each line.
>Your solution prepends only a prefix for the first line.


In that case, the prefix stream at this site does *exactly* what you
want. There's no other good way to do it within the iostreams
heirarchy.
http://www.informatik.uni-konstanz.de/~kuehl/

Tom


Hi,
I visited the page, thanks for the hint. You are right, this is exactly
what I need, even thought its a much more complicate solution than I hoped
to find. Unfortunatly the cited code does not compile on my platform
(Visual C++ .Net 2003), but I try to contact Dietmar Kuehl for a workaround.


Apologies, the code it very out of date and needs fixing for standard
streams. Here's the (hopefully) fixed code (sorry about the annoying
word wrap and tabs):
#ifndef _PRFXSTREAM_H_
#define _PRFXSTREAM_H_
// </PRE>
//----------------------------------------------------------------------------
#include <streambuf>
#include <ios>
#include <ostream>
#include <istream>
#include <vector>
// </PRE>

class prfxbuf: public std::streambuf
{
private:
std::streambuf *i_sbuf; // the actual streambuf used
to read and write chars
unsigned int i_len; // the
length of the prefix
char *i_prfx; // the
prefix
bool i_newline; //
remember whether we are at a new line
int i_cache; // may
cache a read character
std::vector<char> i_buf;

bool skip_prefix();

protected:
int overflow(int);
int underflow();
int uflow();
int sync();

public:
prfxbuf(std::streambuf *sb, const char *prfx);
~prfxbuf();
};
class iprfxstream: public std::istream
{
public:
iprfxstream(std::streambuf *sb, const char *prfx);
~iprfxstream();
};

class oprfxstream: public std::ostream
{
public:
oprfxstream(std::streambuf *sb, const char *prfx);
~oprfxstream();
};

#endif /* _PRFXSTREAM_H_ */

#include <cstring>
#include <vector>
//#include "prfxstream.h"
// </PRE>
//----------------------------------------------------------------------------
// The constructor of the prfxbuf initializes its pointer to the
streambuf
// with the argument sb: It is assumed that this streambuf is
initialized
// correctly. In addition no ownership is assumed for this streambuf.
It
// is not deleted in the destructor. Then the length of the prefix
string
// is cached and the prefix string is copied into a private version:
This
// is done to avoid problems when the user modifies or deletes the
string
// passed as constructor argument. The member i_newline is set to
indicate
// that the processing it at the beginning of a new line: in either
case
// (reading or writing) it starts with a new line. When reading a file
a
// prefix has to be skipped and when writing a file a prefix has to be
// added. EOF is used to indicate that the cache does not contain any
// valid character.
// <BR>
// In the body of the constructor the put area and the get area are
// initialized to be empty: no buffering is done by this streambuf.
All
// buffering is deferred to the actually used streambuf. This makes
sure
// that the function overflow() is called whenever a character is
written
// to this streambuf and that the function underflow() is called
whenever
// a character is read from this streambuf. The put buffer is
specified
// using streambuf::setp() and the get buffer is specified using
// streambuf::setg().
// <PRE>
prfxbuf::prfxbuf(std::streambuf *sb, const char *prfx):
std::streambuf(),
i_sbuf(sb),
i_len(std::strlen(prfx)),
i_prfx(std::strcpy(new char[i_len + 1], prfx)),
i_newline(true),
i_cache(EOF),
i_buf(i_len)
{
setp(0, 0);
setg(0, 0, 0);
}
// </PRE>
// The destructor of prfxbuf has to release the copy of the prefix.
// <PRE>
prfxbuf::~prfxbuf()
{
delete[] i_prfx;
}

bool prfxbuf::skip_prefix()
{
if (i_sbuf->sgetn(&i_buf[0], i_len) != i_len)
return false;
if (std::strncmp(&i_buf[0], i_prfx, i_len))
{
// an expection could be thrown here...
return false;
}
i_newline = false;
return true;
}

int prfxbuf::underflow()
{
if (i_cache == EOF)
{
if (i_newline)
if (!skip_prefix())
return EOF;

i_cache = i_sbuf->sbumpc();
if (i_cache == traits_type::to_int_type('\n'))
i_newline = true;
return i_cache;
}
else
return i_cache;
}

int prfxbuf::uflow()
{
if (i_cache == EOF)
{
if (i_newline)
if (!skip_prefix())
return EOF;

int rc = i_sbuf->sbumpc();
if (rc == traits_type::to_int_type('\n'))
i_newline = true;
return rc;
}
else
{
int rc = i_cache;
i_cache = EOF;
return rc;
}
}

int prfxbuf::overflow(int c)
{
if (c != EOF)
{
if (i_newline)
if (i_sbuf->sputn(i_prfx, i_len) != i_len)
return EOF;
else
i_newline = false;

char cc = traits_type::to_char_type(c);
int rc = i_sbuf->sputc(cc);
if (cc == '\n')
i_newline = true;
return rc;
}
return 0;
}

int prfxbuf::sync()
{
return i_sbuf->pubsync();
}

iprfxstream::iprfxstream(std::streambuf *sb, const char *prfx):
std::istream(new prfxbuf(sb, prfx))
{
}

oprfxstream::oprfxstream(std::streambuf *sb, const char *prfx):
std::ostream(new prfxbuf(sb, prfx))
{
}

iprfxstream::~iprfxstream()
{
delete rdbuf();
}

oprfxstream::~oprfxstream()
{
delete rdbuf();
}
// </PRE>
//----------------------------------------------------------------------------
// <HR>
// Please send comments, suggestions, problem reports, bug fixes etc.
to
// <BR>
// <A HREF="http://www.informatik.uni-konstanz.de/~kuehl"><I>Dietmar
Kühl</I></A>:
// <A
HREF="mailto:di***********@claas-solutions.de">Di***********@claas-solutions.de</A>
// </BODY>
// </HTML>

//test code
#include <iostream>
int main()
{
oprfxstream mystream(std::cout.rdbuf(), "Test prefix: ");
mystream << "This should have been prefixed.\nAlong with this.";
mystream << "\n" << 10 << '\n';
mystream.flush();
}
Jul 19 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Victor Irzak | last post by:
Hello, I have an ABC. it supports: ostream & operator << I also have a derived class that supports this operator. How can I call operator << of the base class for derived object??? Is it...
103
by: Steven T. Hatton | last post by:
§27.4.2.1.4 Type ios_base::openmode Says this about the std::ios::binary openmode flag: *binary*: perform input and output in binary mode (as opposed to text mode) And that is basically _all_ it...
0
by: Steven T. Hatton | last post by:
I tried to create my own manipulator that would both set the width of the subsequent output field, and cast an unsigned char to unsigned in. I came up with the following rather ugly hack. Notice...
10
by: Johannes Barop | last post by:
Hi, I want to format the output of a 'std::ostream', but i dont know how to do it . Example: int main() { my_out << "Hi.\nI'am a" << " Computer."; my_out << "Nice.";
1
by: Johannes Barop | last post by:
Hello, i try to implement a streambuffer. I overwrote streambuf::overflow() and streambuf::xsputn(). Both are protected and virtual (http://www.cplusplus.com/ref/iostream/streambuf/). But...
6
by: Geoffrey S. Knauth | last post by:
It's been a while since I programmed in C++, and the language sure has changed. Usually I can figure out why something no longer compiles, but this time I'm stumped. A friend has a problem he...
2
by: waitan | last post by:
#include <algorithm> #include <iostream> #include <fstream> #include <string> #include <vector> #include <sstream> #include <iterator> #include <iomanip> using namespace std;
6
by: syang8 | last post by:
Any one can specify the problem of the following code? The compiling error is on the friend function. If the base class is not inherited from ostream, or I just remove the friend function from the...
1
by: AJG | last post by:
Hi there. I am using a library called SOCI that has a method to set a stream which it uses to log SQL queries. The signature is as follows: void setLogStream(std::ostream *s); This works great...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.