返回列表 發帖

stringstream 字串串流 (二)

試利用 stringstream 型別,來進行變數型態的轉換,譬如 int 轉 float、double轉 string 等。
stringstream 物件再重複使用前,必須先做初始化 (清空) 的動作。
我們可透過 <typeinfo> 標頭檔所提供的 typeid() 接 name() 函式,查看變數的型態。

  1. #include<iostream>
  2. #include<cstdlib>
  3. #include<sstream>
  4. #include<typeinfo>
  5. using namespace std;
  6. int main()
  7. {
  8.     stringstream ss;
  9.     int a=123;
  10.     double b=456.789;
  11.     float c;
  12.     string d;
  13.    
  14.     ss<<a;
  15.     ss>>c;
  16.     cout<<c<<endl;
  17.      
  18.     ss.str("");   //重複使用前需初始化
  19.     ss.clear();
  20.    
  21.     ss<<b;
  22.     ss>>d;
  23.     cout<<d<<endl;
  24.    
  25.     cout<<typeid(a).name()<<endl;
  26.     cout<<typeid(b).name()<<endl;
  27.     cout<<typeid(c).name()<<endl;
  28.     cout<<typeid(d).name()<<endl;
  29.    
  30.     system("pause");     
  31.     return 0;   
  32. }
複製代碼

返回列表