473,396 Members | 1,805 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,396 software developers and data experts.

Text formatting with streams

I need to create a C++ function that works similar to 'cout'. I would
like to have a function 'MyTextOut' that would accept the following
syntax

MyTextOut << "x = " << iX << " kg" ;

and outputs the concatenated string on a I/O channel defined by me.
Jul 23 '05 #1
7 1582
Dear CSpartan,

On Wed, 2005-07-20 at 09:49 -0700, CSpartan wrote:
I need to create a C++ function that works similar to 'cout'. I would
like to have a function 'MyTextOut' that would accept the following
syntax

MyTextOut << "x = " << iX << " kg" ;

and outputs the concatenated string on a I/O channel defined by me.


This already exists in the standard library. It is called an
ostringstream and can be used as in

#include<sstream>

vector<string> v;
ostringstream ss;
int i=5,j=8;
ss << "f" << i << "_" << j;
v.push_back(ss.str());

Best wishes,
Chris

Jul 23 '05 #2
CSpartan wrote:
I need to create a C++ function that works similar to 'cout'.
You should probably start with learning C++ first... 'cout' is not
a function, it is an object of a class (of 'std::ostream' or derived
thereof) and you apparently want to create a similar class. Note,
however, that this is done differently than you think: you are *not*
going to change 'std::ostream' or derive thereof (well, you might
derive from this class but only for convenient construction; see below)
but you want to derive a class from 'std::streambuf' and use it with
an 'std::ostream'.
I would like to have a function 'MyTextOut' that would accept the
following syntax

MyTextOut << "x = " << iX << " kg" ;

and outputs the concatenated string on a I/O channel defined by me.


IOStreams operate on external representations abstracted using the
class 'std::streambuf' (well, actually it is a class template called
'std::basic_streambuf' but you should probably ignore this detail for
noww and use the typedef 'std::streambuf' thinking of it as a normal
class). For handling output you want to override the virtual function
'sync()' and 'overflow()' which do similar but not identical operations.
In addition, you want to setup a buffer to avoid sending individual
characters. This looks something like this:

class io_channel_buf:
public std::streambuf
{
public:
io_channel_buf() { setp(m_buffer, m_buffer + s_size - 1); }
private:
int overflow(int c)
{
if (traits_type::eq_int_type(c, traits_type::eof()))
{
*pptr() = traits_type::to_char_type(c);
pbump(1);
}
return sync() == -1? traits_type::eof(): traits_type::not_eof(c);
}

int sync()
{
if (pbase() != pptr())
{
int rc = write(channel, pbase(), pptr() - pbase());
if (rc != pptr() - pbase())
return -1; // TODO: possibly deal with partially send buffers...
sep(m_buffer, m_buffer + s_size - 1);
}
return 0;
}

enum { s_size = 1024 };
char m_buffer[s_size];
};

The 'write()' function sends the characters to your I/O channel and
will probably be replaced by whatever approach is suitable to access
this I/O channel. You would then create an 'std::ostream' object which
internally uses this stream buffer for your stream object:

io_channel_buf MyTextBuf;
std::ostream MyTextOut(&MyTextBuf);

MyTextOut << whatever;

To avoid the two step construction of the output object, you might
derive from 'std::ostream' and setup the proper stream buffer in the
constructor of the derived class. You should, however, don't try to
temper with 'std::ostream's functios otherwise than this.

For more details on anything I have written, search for past articles
I have written in comp.lang.c++ or comp.lang.c++.moderated on similar
subjects...
--
<mailto:di***********@yahoo.com> <http://www.dietmar-kuehl.de/>
<http://www.eai-systems.com> - Efficient Artificial Intelligence
Jul 23 '05 #3
The 'streambuf' class seems to be able to do what I want. I tried the
suggested code block, but couldn't make it work. What is missing to
make the following work (writing to standard out) ?

#include <iostream>
#include <io.h>

class io_channel_buf : public std::streambuf
{
public:
io_channel_buf() { setp(m_buffer, m_buffer + s_size - 1); } //
constructor
private:
int overflow(int c)
{
if (traits_type::eq_int_type(c, traits_type::eof()))
{
*pptr() = traits_type::to_char_type(c);
pbump(1);
}
return sync() == -1? traits_type::eof(): traits_type::not_eof(c);
}

int sync()
{
if (pbase() != pptr())
{
int rc = write(1, pbase(), pptr() - pbase());

if (rc != pptr() - pbase())
return -1; // TODO: possibly deal with partially send buffers...

setp(m_buffer, m_buffer + s_size - 1);
}
return 0;
}

enum { s_size = 1024 };
char m_buffer[s_size];
};

void main(void)
{
io_channel_buf MyTextBuf;
std::ostream MyTextOut(&MyTextBuf);
int x = 3;

MyTextOut << "x equals " << x ;
}

Jul 23 '05 #4
I found the problem. I forgot to include a destructor which calls the
sync() to flush buffer.

Thanks for your help, the function now works exactly the way I want.

Jul 23 '05 #5
I entered another problem with the code. Depending on the compiler I
use, the buffer doesn't always get flushed.

If compiled with VC++ 6, then I need to add 'endl' to make the buffer
get flushed (i.e. MyTextOut << whatever << endl).

In VC++ 7 I don't need to include the 'endl' (i.e. MyText << whatever)

Why?

Is there a difference in implementation of streambuf between the two
compilers? How can I make it work with both compiler versions without
the need for 'endl'?

Jul 24 '05 #6
ov*****@hotmail.com wrote:
I entered another problem with the code. Depending on the compiler I
use, the buffer doesn't always get flushed.

If compiled with VC++ 6, then I need to add 'endl' to make the buffer
get flushed (i.e. MyTextOut << whatever << endl).

In VC++ 7 I don't need to include the 'endl' (i.e. MyText << whatever)

Why?

Is there a difference in implementation of streambuf between the two
compilers? How can I make it work with both compiler versions without
the need for 'endl'?


What do you want to do? Flush the buffer without a newline?

MyTextOut << whatever << std::flush;

or

MyTextOut << whatever;
MyTextOut.flush();

Ben
--
Questions by email will likely be ignored, please use the newsgroups.
I'm not just a number. To many, I'm known as a String...
Jul 24 '05 #7
I would like to know why the class behaves differently when compiled in
VC++ 6 compared to VC++ 7.

When compiled in VC++ 6 the following code does not print to stdout

MyTextOut << whatever ;

Recompiling the code using VC++ 7 will give output to the stdout. Why
do I need to force flushing from VC++ 6?

Jul 24 '05 #8

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

Similar topics

2
by: SK | last post by:
Is there a way to store HTML into a MySQL TEXT column, yet be able to search over textual content only? For example, if I store the following HTML snippet: <p>A very <em>small</em>...
1
by: Koen | last post by:
Hi, could anyone please tell me how I can get the equivalent of this: fprintf(aFile,"-20.15g",aDouble); but in C++ using formatted streams? I tried with C++ formatted streams using:...
3
by: Tron Thomas | last post by:
What does binary mode for an ofstream object do anyway? Despite which mode the stream uses, operator << writes numeric value as their ASCII representation. I read on the Internet that it is...
8
by: Dave Moore | last post by:
I realize this is a somewhat platform specific question, but I think it is still of general enough interest to ask it here ... if I am wrong I guess I will find out 8*). As we all know, DOS uses...
11
by: Steven T. Hatton | last post by:
OK, I take back the nasty stuff I said about printf. At least until I see a similarly concise way of writing this using C++ formatters. I want to convert the following to something I can put onto...
7
by: Kayle | last post by:
For preservation of indentation when moving the C source file from Windows to Linux machine, what is the advice to format the code. Should the code formatted using spaces instead of tabs? When...
9
by: anachronic_individual | last post by:
Hi all, Is there a standard library function to insert an array of characters at a particular point in a text stream without overwriting the existing content, such that the following data in...
2
by: subramanian100in | last post by:
In K & R ANSI C book(2nd Edition), in page 241, the following lines are mentioned. "The library supports text streams and binary streams, although on some systems, notably UNIX, these are...
1
by: blangela | last post by:
Bjarne Stroustrup has a new text coming out called "Programming: Principles and Practice Using C++" (ISBN: 0321543726), due to be published in December of this year. Some of the features of this...
4
by: zr | last post by:
Hi, i need to read a text file which contains a list of items, all of type ItemType, separated by whitespace and newlines. For each line, there will be a vector<ItemTypeobject that will store...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.