Partager via


Constructing Output Stream Objects

If you use only the predefined cout, cerr, or clog objects, you do not need to construct an output stream. You must use constructors for:

  • Output File Stream Constructors

  • Output String Stream Constructors

Output File Stream Constructors

You can construct an output file stream in one of two ways:

  • Use the default constructor, and then call the open member function.

    ofstream myFile; // Static or on the stack
    myFile.open( "filename" );
    
    ofstream* pmyFile = new ofstream; // On the heap
    pmyFile->open( "filename" );
    
  • Specify a filename and mode flags in the constructor call.

    ofstream myFile( "filename", ios_base::out);
    

Output String Stream Constructors

To construct an output string stream, you can use one of two ostrstream constructors. One dynamically allocates its own storage, and the other requires the address and size of a preallocated buffer.

  • The dynamic constructor is used in the following way:

    char* sp;
    ostrstream myString;
    mystring << "this is a test" << ends;
    sp = myString.str();  // Get a pointer to the string
    

    The ends "manipulator" adds the necessary terminating null character to the string.

  • The constructor that requires the preallocated buffer is used in the following way:

    char s[32];
    ostrstream myString( s, sizeof( s ) );
    myString << "this is a test" << ends; // Text stored in s
    

See Also

Concepts

Output Streams