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:
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);
To construct an output string stream, you can use ostringstream in the following way:
using namespace std; string sp; ostringstream myString; myString << "this is a test" << ends; sp = myString.str(); // Obtain string cout << sp < endl;
The ends "manipulator" adds the necessary terminating null character to the string.