Sometimes it is very convenient to use stringstream to convert between strings and other numerical types. The usage of stringstream
is similar to the usage of iostream
, so it is not a burden to learn.
Stringstreams can be used to both read strings and write data into strings. It mainly functions with a string buffer, but without a real I/O channel.
The basic member functions of stringstream class are
str()
, which returns the contents of its buffer in string type.
str(string)
, which set the contents of the buffer to the string argument.
Here is an example of how to use string streams.
ostringstream os;
os << "dec: " << 15 << " hex: " << std::hex << 15 << endl;
cout << os.str() << endl;
The result is dec: 15 hex: f
.
istringstream
is of more or less the same usage.
To summarize, stringstream is a convenient way to manipulate strings like an independent I/O device.
FYI, the inheritance relationships between the classes are:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…