iostream examples

iostream incore formatting

Despite its name, the iostream library may be used in situations that do not involve input or output. In particular, it can be used for ``incore formatting'' operations in arrays of characters. These operations are supported by the classes istrstream and ostrstream, which are derived from istream and ostream respectively. The examples of this subtopic assume that the header file strstream.h has been included.

For example, to interpret the contents of the string argv[1] as an integer value, the code might look like:

   int i ;
   istrstream(argv[1]) >> i ;

The argument of the istrstream() constructor is a char pointer. In this example, there is no need for a named strstream. An anonymous constructor is more direct.

The inverse operation, taking a value and converting it to characters that are stored into an array, is also possible. For example,

   char s[32] ;
   ostrstream(s,sizeof(s)) << x << ends ;
will store the character representation of x in s with a terminating null character supplied by the ends (endstring) manipulator. The iostream library requires that a size be supplied to the constructor and nothing is ever stored outside the bounds of the supplied array. In this case, an ``output error'' will occur if an attempt is made to insert more than 32 characters.

In case it is inconvenient to preallocate enough space for the string, a program can use an ostrstream() constructor without any arguments. For example, suppose we want to read the entire contents of a file into memory.

   ifstream in("infile") ;

// strstream with dynamic allocation strstream incore ;

char c ; while ( incore && in.get(c) ) incore.put(c) ;

// str returns pointer to allocated space char* contents = incore.str() ; ... // once str is called space belongs to caller delete contents ;

The file infile is read and its contents inserted into incore. Space will be allocated using the ordinary C++ allocation (operator new) mechanism, and automatically increased as more characters are inserted. incore.str() returns a pointer to the currently allocated space and also ``freezes'' the strstream so that no more characters can be inserted. Until incore is frozen, it is the responsibility of the strstream() destructor to free any space that might have been allocated. But after the call to str(), the space becomes the caller's responsibility.
Next topic: Predefined streams
Previous topic: Files

© 2004 The SCO Group, Inc. All rights reserved.
UnixWare 7 Release 7.1.4 - 27 April 2004