Scroll to navigation

std::strstream::strstream(3) C++ Standard Libary std::strstream::strstream(3)

NAME

std::strstream::strstream - std::strstream::strstream

Synopsis


strstream(); (1)
strstream(char* s, int n, std::ios_base::openmode mode (2)
= std::ios_base::in | std::ios_base::out);


Constructs new input/output strstream and its underlying std::strstreambuf.


1) Default-constructs the underlying std::strstreambuf, which creates a dynamically
growing buffer, and initializes the base class with the address of the strstreambuf
member.
2) Initialized the base class with the address of the underlying std::strstreambuf
member, which is initialized in one of the two possible ways, both of which use a
user-provided fixed-size array:
a) if the app bit is not set in mode, constructs the buffer by calling
strstreambuf(s, n, s). The behavior is undefined if there are less than n elements
in the array whose first element is pointed to by s
b) if the app bit is set in mode, constructs the buffer by calling strstreambuf(s,
n, s + std::strlen(s)). The behavior is undefined if there are less than n elements
in the array whose first element is pointed to by s or if the array does not contain
a valid null-terminated character sequence.

Parameters


s - char array to use as the output buffer
n - size of the array to be used for output
specifies stream open mode. It is a bitmask type, the following constants are
defined (although only app is used):


Constant Explanation
mode - app seek to the end of stream before each write
binary open in binary mode
in open for reading
out open for writing
trunc discard the contents of the stream when opening
ate seek to the end of stream immediately after open

Example

// Run this code


#include <iostream>
#include <strstream>
#include <string>


int main()
{
// dynamic buffer
std::strstream s1; // dynamic buffer
s1 << 1 << ' ' << 3.14 << " example" << std::ends;
std::cout << "buffer holds '" << s1.str() << "'\n";
s1.freeze(false);


int n; double d;
std::string w;
s1 >> n >> d >> w;
std::cout << "Read back: n = " << n
<< " d = " << d
<< " w = '" << w << "'\n";


// static buffer
char arr[20] = "-1 -3.14 ";
std::strstream s2(arr, sizeof arr, std::ios_base::app);
s2 << "another" << std::ends;
std::cout << "buffer holds: '" << s2.str() << "'\n";
s2 >> n >> d >> w;
std::cout << "Read back: n = " << n
<< " d = " << d
<< " w = '" << w << "'\n";
}

Output:


buffer holds '1 3.14 example'
Read back: n = 1 d = 3.14 w = 'example'
buffer holds: '-1 -3.14 another'
Read back: n = -1 d = -3.14 w = 'another'

See also


constructor constructs a strstreambuf object
(public member function of std::strstreambuf)
constructor constructs an strstream, optionally allocating the buffer
(public member function of std::istrstream)
constructor constructs an strstream, optionally allocating the buffer
(public member function of std::ostrstream)

2022.07.31 http://cppreference.com