Partager via


Constructing Output Stream Objects

 

The latest version of this topic can be found at 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 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.

See Also

Output Streams