c++stringstream任意類型轉換,用於C++風格的字符串的輸入輸出

實現任意類型的轉換

 

 

    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函數參數:需要讀取字符串的最大長度,需要忽略的字符

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章