Prior to the conversion of string and int in Leetcode, Istringstream was used, and now a general summary of usage and test cases.
Introduction: C + + introduced the Ostringstream, Istringstream, StringStream these three classes, to use them to create objects must include sstream.h header files.
The Istringstream class is used to perform input operations on C + +-style streaming.
The Ostringstream class is used to perform the output operation of a C-style streaming stream.
The StringStream class can also support the C-style streaming input and output operation.
The following figure describes in detail the inheritance relationships between several species:
Istringstream is constructed from a string object that reads characters from a string object.
Ostringstream also has a string object constructed to insert characters into a string object.
StringStream is the input and output of a C + + style string.
Code test:
#include <iostream> #include <sstream> using namespace std;<pre name= "code" class= "CPP" >int main () {
String test = " -123 9.87 Welcome to, 989, test!";
Istringstream Iss;//istringstream provides read-string functionality Iss.str (test);//Copy String test to ISS, return void string s;
cout << "Read the string by space:" << Endl; While (ISS >> s) {cout << s << endl;//read string by space} cout << "*********************"
;< Endl;
Istringstream STRM (test);
Create the StringStream object that stores the copy of test: int i;
float F;
char c;
Char buff[1024];
STRM >> i;
cout << "Reading int type:" << i << Endl;
STRM >> F;
cout << "read float type:" <<f << Endl;
STRM >> C;
cout << "read char type:" << c << Endl;
STRM >> Buff;
cout << "Read buffer type:" << buff << Endl;
Strm.ignore (100, ', ');
Int J;
STRM >> J; cout << "Ignore", ' read int type: ' << J <<
Endl
System ("pause");
return 0; }
Output:
Summarize:
1 in the Istringstream class, when constructing a string stream, the space becomes the inner boundary of the string parameter;
2) Istringstream classes can be used as string and various types of conversion pathways
3 Ignore function parameter: need to read the maximum length of the string, need to ignore the characters
Code test:
int main () {
ostringstream out;
Out.put (' t ');//Insert character
out.put (' e ');
Out << "St";
string res = OUT.STR ();//Fetch strings;
cout << res << Endl;
System ("pause");
return 0;
Output: test string;
Note: If you initialize Ostringstream at the beginning, such as Ostringstream out ("test"), then the string that is put or << will overwrite the original character, and the more than the part is added on the original basis.
StringStream Similarly, all three classes can be used for strings and different types of conversions.
The above is a small series for everyone to bring the use of C + + StringStream and examples of all content, I hope that we support cloud-Habitat Community ~