Constructing Output Stream Objects
Visual Studio 2015
The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.
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:
You can construct an output file stream in one of two ways:
- Use the default constructor, and then call the
openmember 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.
Show: