C++引入ostringstream、istringstream、stringstream這三個類,要使用他們創建對象就必須包含<sstream>這個頭文件。
istringstream的構造函數原形如下:
istringstream::istringstream(string str);
它的作用是從string對象str中讀取字符,stringstream對象可以綁定一行字符串,然后以空格為分隔符把該行分隔開來。
下面我們分離以空格為界限,分割一個字符串。
#include<iostream> #include<sstream> #include<string> int main() { std::string str = "I am coding ..."; std::istringstream is(str); do { std::string substr; is>>substr; std::cout << substr << std::endl; } while (is); return 0; }
程序輸出
I
am
coding
...
另外用vector也可以實現
#include <vector> #include<iostream> #include <string> #include <sstream> using namespace std; int main() { string str("I am coding ..."); string buf; 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; }
補充知識點,自己積累學習
在類型轉換中使用模板
你可以輕松地定義函數模板來將一個任意的類型轉換到特定的目標類型。例如,需要將各種數字值,如int、long、double等等轉換成字符串,要使用以一個string類型和一個任意值t為參數的to_string()函數。to_string()函數將t轉換為字符串並寫入result中。使用str()成員函數來獲取流內部緩沖的一份拷貝:
template<class T> void to_string(string & result,const T& t) { ostringstream oss;//創建一個流 oss<<t;//把值傳遞如流中 result=oss.str();//獲取轉換后的字符轉並將其寫入result }
這樣,你就可以輕松地將多種數值轉換成字符串了:
to_string(s1,10.5);//double到string
to_string(s2,123);//int到string
to_string(s3,true);//bool到string
可以更進一步定義一個通用的轉換模板,用於任意類型之間的轉換。函數模板convert()含有兩個模板參數out_type和in_value,功能是將in_value值轉換成out_type類型:
template<class out_type,class in_value> out_type convert(const in_value & t) { stringstream stream; stream<<t;//向流中傳值 out_type result;//這里存儲轉換結果 stream>>result;//向result中寫入值 return result; }
這樣使用convert():
double d;
string salary;
string s=”12.56”;
d=convert<double>(s);//d等於12.56
salary=convert<string>(9000.0);//salary等於”9000”
