I used to think that stringstream is far inferior to sprintf.
Recently, it suddenly sprouted to see if stirngstream is really as bad as I thought.
Let's take a look at the comparison.
// Stringstream.
Stringstream sstream; sstream <1 <"abcc"; string str = sstream. str (); // number, string mixed.
Sstream <"123 ";
Sstream> num; // string to numeric.
// Sprintf.
string str(512, 0);sprintf(&str[0], "%s%d", s, d);
sprintf(&str[0], "%[^a-z]%*[a-z]%[^a-z]%*[a-z]%[^\0]", "2014-asddsaqwfdsf6-qweljkhdkjfhs29");
// Sscanf.
sscanf("123", "%d", &num);
Compare the above Code.
Stringstream:
Provides the function of converting numbers and strings to each other.
String is supported perfectly. You do not need to know the buffer size in advance.
Sprintf, sscanf.
The buffer size needs to be set in advance, which is a little weaker than the former.
Supports quite limited but very powerful regular expressions.
If you see this, Have you guessed the result.
In fact, stringstream is quite powerful, but you don't know...
Let's take a look at the following example.
template<class T1, class T2>
inline T1 parseTo(const T2 t)
{
static stringstream sstream;
T1 r;
sstream << t;
sstream >> r;
sstream.clear();
return r;
}
int i = parseTo<int>("123");
float f = parseTo<float>("1.23");string str = parseTo<string>(123);
Have you found that this method is convenient and elegant.
The real strength of stringstream is still behind the scenes ..
class date {public: int year; int month; int day;};stringstream &operator<<(stringstream &sstream, const date &d){ sstream << d.year << d.month << d.day;}stringstream &operator>>(stringstream &sstream, date &d){ sstream >> d.year >> d.month >> d.day; return sstream;}
Stringstream is scalable.
Through the C ++ overload operator, any custom class can be converted through stringstream.
Let's take a look...
sstream << "2014";
sstream << "asddsaqwfdsf6qweljkhdkjfhs29";
string str = regex_replace(sstream.str(), "[a-zA-Z]+", "-");
An inappropriate example is given.
Str = ";
In its own encapsulation, stringstream supports a complete regular expression...
Sprintf, sscanf ....