io/charstr1.cpp

The following code example is taken from the book
Object-Oriented Programming in C++
by Nicolai M. Josuttis, Wiley, 2002
© Copyright Nicolai M. Josuttis 2002


#include <iostream>
#include <strstream>

int main()
{
    // create dynamic char* stream for writing
    std::ostrstream buffer;

    // write formatted string and append end-of-string character
    buffer << "Pi: " << 3.1415 << std::ends;

    /* output character string
     * - str() freezes the char* stream
     */
    std::cout << buffer.str() << std::endl;

    // cancel the freezing
    buffer.freeze(false);

    // position so that std::ends is overwritten
    buffer.seekp(-1,std::ios::end);

    // write into char* stream further
    buffer << " or also: " << std::scientific << 3.1415
           << std::ends;

    /* output character string
     * - str() freezes the char* stream
     */
    std::cout << buffer.str() << std::endl;

    // cancel the freezing, so that memory is freed by char* stream destructor
    buffer.freeze(false);
}