實現任意類型的轉換
template<typename out_type, typename in_value>
out_type convert(const in_value & t){
stringstream stream;
stream<<t;//向流中傳值
out_type result;//這裏存儲轉換結果
stream>>result;//向result中寫入值
return result;
}
例子:
#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提供讀 string 的功能
iss.str(test);//將 string 類型的 test 複製給 iss,返回 void
string s;
cout << "按照空格讀取字符串:" << endl;
while (iss >> s){
cout << s << endl;//按空格讀取string
}
system("pause");
return 0;
}
總結:
1)在istringstream類中,構造字符串流時,空格會成爲字符串參數的內部分界;
2)istringstream類可以用作string與各種類型的轉換途徑
3)ignore函數參數:需要讀取字符串的最大長度,需要忽略的字符