C + + introduces Ostringstream, Istringstream, StringStream these three classes, to use them to create an object must include <sstream> this header file.
The Istringstream constructor is as follows:
Istringstream::istringstream (string str);
Its function is to read the characters from the String Object str, the StringStream object can bind a line of strings, and then separate the line with a space delimiter.
Let's separate a string by dividing it with a space.
#include <iostream>#include<sstream>#include<string>intMain () {std::stringstr ="I am Coding ..."; Std::istringstream is(str); Do{std::stringsubstr; is>>substr; Std::cout<< substr <<Std::endl; } while( is); return 0;}
Program output
I
Am
Coding
...
In addition, vector can also be used to achieve
#include <vector>#include<iostream>#include<string>#include<sstream>using namespacestd;intMain () {stringStr"I am Coding ..."); stringbuf; StringStream SS (str); Vector<string>VEC; while(SS >>buf) Vec.push_back (BUF); for(vector<string>::iterator iter = Vec.begin (); Iter! = Vec.end (); ++ITER) {cout<< *iter <<Endl; } return 0;}
Add knowledge points, accumulate learning by yourself
Using templates in type conversions
You can easily define a function template to convert an arbitrary type to a specific target type. For example, you need to convert various numeric values, such as int, long, double, and so on, to a string, using the to_string () function with a string type and an arbitrary value of T as the argument. The to_string () function converts t to a string and writes to result. Use the STR () member function to get a copy of the stream's internal buffer:
template<class t>void to_string (string & result,const t& T) { ostringstream oss; // Create a Stream oss<<t; // Pass the value to the stream result=oss.str (); // gets the converted character to go and writes it to result}
In this way, you can easily convert a number of values to a string:
To_string (s1,10.5);//double to String
To_string (s2,123);//int to String
To_string (s3,true);//bool to String
You can further define a generic transformation template for conversions between any type. The function template convert () contains two template parameters Out_type and In_value, which is the function of converting in_value values into Out_type types:
template<class Out_type,class in_value>out_type CONVERT (const In_value & t) { stringstream stream; Stream<<t; // passing values to the stream out_type result; // The conversion results are stored here Stream>>result; // write value to result return result;}
This uses convert ():
Double D;
string salary;
String s= "12.56";
D=convert<double> (s);//d equals 12.56
Salary=convert<string> (9000.0);//salary equals "9000"
Handling strings in C + + Sstream