Constructing Input Stream Objects

If you use only cin, then you don't have to worry about input stream construction. If you use file streams or string streams, then constructors are important.

Input File Stream Constructors

If you need an input file stream, you have three choices:

You can use the void-argument constructor, then call the open member function.

ifstream myFile; // On the stack

myFile.open( "filename", iosmode );

ifstream* pmyFile = new ifstream; // On the heap

pmyFile->open( "filename", iosmode );

You can specify a filename and mode flags in the constructor invokation, thereby opening the file during the construction process.

ifstream myFile( "filename", iosmode );

You can specify an integer file descriptor for a file that is already open for input. In this case you have the option to specify unbuffered input or a pointer to your own buffer.

int fd = _open( "filename", dosmode );

ifstream myFile1( fd ); // Buffered mode (default)

ifstream myFile2( fd, NULL, 0 ); // Unbuffered mode

ifstream myFile3( fd, pch, buflen ); // User-supplied buffer

For a description of mode flag usage, see the description of the open member function in “Output Streams” on page 365.

Input String Stream Constructors

The input string stream constructor requires the address of preallocated, preinitialized storage:

char s[] = "123.45";

double amt;

istrstream myString( s );

myString >> amt; // Amt should contain 123.45