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 () {St
Ring 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 spaces} cout << "*********************" << E
Ndl
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: Summary: 1 in the Istringstream class, when the string stream is constructed, the space becomes the inner boundary of the string parameter; 2 the Istringstream class can be used as a string with various types of conversion path 3) Ignore function arguments: the maximum length required to read a string , you need to ignore the character 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 the first initialization of ostringstream, such as Ostringstream out ("test"), then the put or << string will overwrite the original character, more than the part of the original base increase.
StringStream Similarly, all three classes can be used for strings and different types of conversions.