The iostream library supports in-memory input/output
, in which a stream is attached to a string within the program’s memory. That string can be written to and read from using the iosteam input and output operators. The library defines three kinds of string streams:
1)
istringstream
, derived from istream
, reads from a string
.
2)
ostringstream
, derived from ostream
, writes to a string
.
3)
stringstream
, derived from iostream
, reads and writes a string
.
[Note]
To use any of these classes, we must include the sstream
header.
stringstream-Specific Operations
stringstream strm
;
Creates an unbound stringstream.
stringstream strm(s)
;
Creates a stringstream that holds a copy of the string s.
strm.str()
Returns a copy of the string that strm holds.
strm.str(s)
Copies the string s into strm. Returns void.
stringstreamS Provide Conversions and/or Formatting
One common use of stringstreamS is when we want to obtain automatic formatting across multiple data types. For example, we might have a collection of numeric values but want their string representation or vice versa. The sstream input and output operations automatically convert an arithmetic type into its corresponding string representation or back again.
Here we create an empty ostringstream object named format_message and insert the indicated text into that object. What’s important is that the int values are automatically converted to their printable string equivalents. The contents of format_message can be obtained from using the member str() to get the string from format_message.
[Note] To read input_string, we must parse the string into its component parts. We want the numeric values; to get them we must read (and ignore) the labels that are interspersed with the data we want.