Wednesday, December 18, 2024

basic_stringbuf

Overview
basic_stringbuf is a template based class used for read from or/and write to strings in the memory.

Details
istringstream, ostringstream and stringstream  classes uses a basic_stringbuf to  read from or/and write to strings. It's derived from basic_streambuf class.

Syntax
template<class CharT, class Traits = char_traits<CharT>, class Alloc = allocator<CharT>> 
class basic_stringbuf:public basic_streambuf<CharT,Traits> 
where CharT can be char or wchar_t

Properties
Following properties are defined. 
NameDefinition
char_typechar,wchar_t
traits_typechar_traits<char_type>
allocator_typeallocate<char_type>
int_typechar_traits<char_type>::int_type
pos_typechar_traits<char_type>::pos_type
off_typechar_traits<char_type>::off_type

openmode
The openmode flags indicate how the streams such as disk files or memory streams can be opened for IO operations such as read, write or append.  These are used in calls such as fopen(). These are bitmask type flags that can be ORed. The following describes different values.
NameDescription
inOpen file for reading.
outOpen file for writing.
ateSet the stream's position indicator to the end of the stream on opening.
appSet the stream's position indicator to the end of the stream before each output operation.
truncAny current content is discarded, assuming a length of zero on opening.
binaryConsider stream as binary rather than text.
Note it's possible to have multiple flags set. i.e., in | out set at the same time.

Note that in case of ate, writes can be on done anywhere in the stream. For example, begin or middle. In case of app, writes can be done only in the end.
Note that difference between text and binary files is that in a text file individual lines are demarcated by a newline character \n or \r\n. In case of binary files there are no such demarcation.


Constructor
NameDescription
  1. basic_istringbuf
    (ios_base::openmode mode = ios_base::in | ios_base::out)
  2. basic_istringbuf
    (const basic_string& s,
    ios_base::openmode mode = ios_base::in ios_base::out)
  1. Constructs an empty basic_stringbuf object.
  2. Constructs basic_stringbuf object with the content from s.
The mode constants are defined in ios_base class.

Example
stringbuf s, s2 {"hello, world!"};

Methods
These are the public functions available for the clients like istringstreamostringstream and stringstream classes.

NameDescription
  1. void str
    (
    const basic_string& s) 

  2. basic_string str()
  1. Sets the current contents of the stream to s
  2. Returns the current contents of the stream as string.
Example
stringbuf ss,ss2;
ss.str("hello, world!");
ss2.str(ss.str());


No comments:

Post a Comment