473,763 Members | 1,882 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 10361


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******@jippi i.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******@jippi i.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********@hot mail.com> wrote in message news:<m8******* *************** **********@4ax. com>...
On 15 Oct 2003 09:00:51 -0700, go***@nexgo.de (Boris) wrote:
Bob Smith <bo******@jippi i.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********@hot mail.com> wrote in message news:<m8******* *************** **********@4ax. com>...
On 15 Oct 2003 09:00:51 -0700, go***@nexgo.de (Boris) wrote:
>Bob Smith <bo******@jippi i.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<cha r> i_buf;

bool skip_prefix();

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

public:
prfxbuf(std::st reambuf *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::prfxbu f(std::streambu f *sb, const char *prfx):
std::streambuf( ),
i_sbuf(sb),
i_len(std::strl en(prfx)),
i_prfx(std::str cpy(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::~prfxb uf()
{
delete[] i_prfx;
}

bool prfxbuf::skip_p refix()
{
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::underf low()
{
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::overfl ow(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::ip rfxstream(std:: streambuf *sb, const char *prfx):
std::istream(ne w prfxbuf(sb, prfx))
{
}

oprfxstream::op rfxstream(std:: streambuf *sb, const char *prfx):
std::ostream(ne w prfxbuf(sb, prfx))
{
}

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

oprfxstream::~o prfxstream()
{
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>Diet mar
Kühl</I></A>:
// <A
HREF="mailto:di ***********@cla as-solutions.de">D i***********@cl aas-solutions.de</A>
// </BODY>
// </HTML>

//test code
#include <iostream>
int main()
{
oprfxstream mystream(std::c out.rdbuf(), "Test prefix: ");
mystream << "This should have been prefixed.\nAlon g 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
8266
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 at all possible?
103
48746
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 says about it. What the heck does the binary flag mean? -- If our hypothesis is about anything and not about some one or more particular things, then our deductions constitute mathematics. Thus mathematics may be defined as the subject in...
0
1516
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 that I am instantiating UI before any call to out.operator<<(). Is there a better way to accomplish this? What I'd like is something I could simply place in the output call between '<<' operators without having to instantiate it first. The...
10
9667
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
2528
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 somehow my OutBuf::xsputn() is not beeing used. But the orginal basic_streambuf::xsputn() calls my OutBuf::overflow(). http://pastebin.com/483016 - OutBuf.h
6
10047
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 hoped I could solve, and I couldn't. Some code he's using, written in 1999, that compiled fine in 1999, no longer does in 2006 with g++ 4. This little bit of code: SimS::SimS (ostream &s) {
2
2957
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
4728
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 base class, the code will compile. ------------------------------------------------------------------------- #include <iostream> template<class Tclass base; template<class Tstd::ostream& operator<< (std::ostream&, base<T>&);
1
3445
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 when used with something like setLogStream(&std::cerr). However, I would like to add more context to the query logged. Specifically, I'd like to add the thread ID. So, instead of the query logged looking like:
0
9566
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9389
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10003
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8825
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7370
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6643
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5271
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5410
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2797
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.