description | title | ms.date | helpviewer_keywords | ms.assetid | |
---|---|---|---|---|---|
Learn more about: Constructing Output Stream Objects |
Constructing Output Stream Objects |
11/04/2016 |
|
93c8eab6-610c-4f48-b76d-1d960cac7641 |
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;
// ...
ostringstream myString;
myString << "this is a test" << ends;
string sp = myString.str(); // Obtain string
cout << sp << endl;
The ends
"manipulator" adds the necessary terminating null character to the string.