LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   [C++] buffers streams (https://www.linuxquestions.org/questions/programming-9/%5Bc-%5D-buffers-streams-333376/)

Ossar 06-14-2005 04:41 AM

[C++] buffers streams
 
Lets say I have a "char * buffer". My problem is how do I tie an ostream to a streambuf so that I can write the buffer of characters to this streambuf.

buffer -> ostream -> streambuf

The streambuf is used by other objects to fetch data for further processing.

I have tried something like this:
Code:

streambuf * sb;
ostream os(sb);
char * buffer = "Hello";

os.write(buffer, 5);
os.flush();
cout << sb;

Not working!

rjlee 06-14-2005 12:27 PM

First off, the value in the pointer sb is undefined. On some compilers this will be 0 or some other predetermined value, on others it will be whatever happened to be in the memory before.

You should never use a pointer before setting it's value; this includes passing it to a constructor or function.

None of the standard << operator methods take a pointer to an object as far as I recall (although they will accept a pointer to a NULL-terminated string in a char array).

From the standard, 27.5 Para 1:
Quote:

The header <streambuf> defines types that control input from and output to character sequences
streambuf is a specialization of basic_streambuf<class charT, class traits> to work with char streams. It takes an input stream, buffers it, and writes it to an output stream when the buffer gets full. You haven't set an output stream in the above code, so it's not clear what your code should do if the pointer were valid.

basic_streambuf also has only a protected constructor, meaning that it can only be created as a base class. I guess this is probably why you're trying to use a pointer here. This won't work; you really do need an object of type streambuf — and that means creating a subclass object like filebuf or stringbuf.

It seems to me like what you want to be using here is an stringbuf, which gives stream access to a character string.

As an aside, I recommend using the std::string class over a NULL-terminated char array; it makes it much easier to trap errors when pointers get out of bounds or buffers overflow, and the overhead is really very small compared to the power of most modern PCs. (Some embedded PCs may be a special case).


All times are GMT -5. The time now is 01:32 PM.