1. 程式人生 > >C++學習筆記——string型 到 int,double,float型的相互轉換:ostringsream,istringstream,stringstream

C++學習筆記——string型 到 int,double,float型的相互轉換:ostringsream,istringstream,stringstream

標頭檔案#include<sstream>
istringstream類:用於執行C++風格的串流的輸入操作。
ostringstream類:用於執行C風格的串流的輸出操作。
strstream類:同時可以支援C風格的串流的輸入輸出操作。
這裡寫圖片描述

istringstream的功能:string型到 int,double,float型的轉換

#include<iostream> 
#include <sstream> 
#include<string>
using namespace std; 
int main()   
{ 
    istringstream
istr; string A; A="1 321.7"; istr.str(A); //上述兩個過程可以簡單寫成 istringstream istr("1 56.7"); cout << istr.str()<<endl; int a; float b; istr>>a; cout<<a<<endl; istr>>b; cout<<b<<endl; system("pause"); return
0; }

輸出結果為:這裡寫圖片描述
主要功能是完成了從string型到int 和 float型的轉換

ostringstream的功能:int double 型等轉化為字串

#include<iostream> 
#include <sstream> 
#include<string>
using namespace std; 
int main()   
{ 
    int a,b;
    string Str1,Str2;
    string Input="abc 123 bcd 456 sss 999";
    //ostringstream 物件用來進行格式化的輸出,可以方便的將各種型別轉換為string型別
//ostringstream 只支援<<操作符 //----------------------格式化輸出--------------------------- ostringstream oss; oss<<3.14; oss<<" "; oss<<"abc"; oss<<55555555; oss<<endl; cout<<oss.str(); system("pause"); //-----------------double型轉化為字串--------------------- oss.str("");//每次使用前清空,oss.clear()並不能清空記憶體 oss<<3.1234234234; Str2=oss.str(); cout<<Str2<<endl; system("pause"); //-----------------int型轉化為字串--------------------- oss.str("");//每次使用前清空,oss.clear()並不能清空記憶體 oss<<1234567; Str2=oss.str(); cout<<Str2<<endl; system("pause"); //-------------------------------------------------------- return 0; }

執行結果:這裡寫圖片描述

stringstream的功能:1)string與各種內建型別資料之間的轉換

#include <iostream> 
#include <sstream> 
#include <string> 
using namespace std; 

int main()   
{ 
     stringstream sstr; 
//--------int轉string----------- 
    int a=100; 
    string str; 
     sstr<<a; 
     sstr>>str; 
    cout<<str<<endl; 
//--------string轉char[]-------- 
     sstr.clear();//如果你想通過使用同一stringstream物件實現多種型別的轉換,請注意在每一次轉換之後都必須呼叫clear()成員函式。 
    string name = "colinguan"; 
    char cname[200]; 
     sstr<<name; 
     sstr>>cname; 
     cout<<cname; 
     system("pause"); 
}

執行結果:這裡寫圖片描述

stringstream的功能:2)通過put()或者左移操作符可以不斷向ostr插入單個字元或者是字串,通過str()函式返回增長過後的完整字串資料,但值 得注意的一點是,當構造的時候物件內已經存在字串資料的時候,那麼增長操作的時候不會從結尾開始增加,而是修改原有資料,超出的部分增長。

#include <iostream> 
#include <sstream> 
#include <string> 
using namespace std; 

int main()   
{ 
     stringstream ostr("ccccccccc"); 
     ostr.put('d'); 
     ostr.put('e'); 
     ostr<<"fg"; 
    string gstr = ostr.str(); 
    cout<<gstr<<endl; 
    char a; 
    ostr>>a; 
    cout<<a ;  
    system("pause");
    return 0;
}

執行結果:這裡寫圖片描述