頭文件:#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;
}
運行結果: