The iostreams facility supports not only input and output to external devices like files. It also allows in-memory parsing and formatting. Source and sink of the characters read or written becomes a string held somewhere in memory. You use in-memory I/O if the information to be read is already available in the form of a string, or if the formatted result is processed as a string. For example, to interpret the contents of the string argv[1] as an integer value, the code might look like this:
int i; if (istringstream(argv[1]) >> i) //1 // use the value of i
//1 | The parameter of the input string stream constructor is a string; here a character array, namely argv[1], is provided as an argument and is implicitly converted to a string. From this newly constructed input string stream, which contains argv[1], an integer value is extracted. |
The inverse operation, taking a value and converting it to characters that are stored in a string, might look like this:
struct date { int day,month,year; } today = {8,4,1996}; ostringstream ostr; //1 ostr << today.month << '-' << today.day <<'-' << today.year; //2 if (ostr) display(ostr.str()); //3
//1 | An output string stream is allocated. |
//2 | Values are inserted into the output string stream. |
//3 | The result of the formatting can be retrieved in the form of a string, which is returned by str(). |
As with file streams, there are three class templates that implement string streams: basic_istringstream <charT,traits,Allocator>, basic_ostringstream <charT,traits,Allocator>, and basic_stringstream <charT,traits,Allocator>. These are derived from the stream base classes, basic_istream <charT, traits>, basic_ostream <charT, traits>, and basic_iostream <charT, traits>. Therefore they inherit all the functions for formatted input and output described in Chapter 7, as well as the stream state. They also have functions for setting and retrieving the string that serves as source or sink, and constructors that allow you to set the string before construction time. For convenience, there are the regular typedefs istringstream, ostringstream, and stringstream, with wistringstream, wostringstream, and wstringstream for the respective tiny and wide character string streams.
The buffering is done through a specialized stream buffer class, basic_stringbuf <charT,traits,Allocator>.
OEM Edition, ©Copyright 1999, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.