標籤:
istringstream、ostringstream、stringstream 類介紹
(1)基於控制台的輸入輸出
iostream對流進行讀寫,由istream和ostream派生。
(2)基於檔案的輸入輸出
標頭檔為fstream,ifstream從檔案中讀取,由istream派生
ofstream寫到檔案中去,由ostream派生,fstream對檔案進行讀寫,由iostream派生
(3)基於字串的輸入輸出
istringstream從string對象中讀取,由istream派生,ostringstream寫入string對象中,由ostream派生,
stringstream對string對象進行讀寫,由iostream派生
istringstream類
字串對象的初始化
istringstream a("2371");
常用的成員函數
str():使istringstream對象返回一個string字串
比如這樣:
istringstream a("2371");cout<<a.str()<<endl;
應用1:把字串類型的資料轉換為其他類型
#include <iostream>#include <algorithm>#include <cstdlib>#include <cstdio>#include <string>#include <cstring>#include <cmath>#include <ctime>#include <set>#include <sstream>using namespace std;int main(){istringstream a("1 2.33");//cout<<a.str()<<endl; string b; b = a.str(); int x; double y; /*a >> x; a >> y; cout<<x<<endl; cout<<y<<endl;*/ a >> y; a >> x; cout<<x<<endl; cout<<y<<endl;return 0;}
應用2:把長字串讀入流中,再從流中把以空格分隔的單詞讀入字串。
#include <iostream>#include <algorithm>#include <cstdlib>#include <cstdio>#include <string>#include <cstring>#include <cmath>#include <ctime>#include <set>#include <sstream>using namespace std;#define read() freopen("data.in", "r", stdin)int main(){//read();istringstream a;string b,str; while(getline(cin,b)) { a.str(b);//把b中de字串存入字元流中 while(a >> str)//每次讀取一個以空格分隔的單詞存入str中 { cout<<str<<endl; } }return 0;}
istringstream類
用來往流中寫入資料
#include <iostream>#include <algorithm>#include <cstdlib>#include <cstdio>#include <string>#include <cstring>#include <cmath>#include <ctime>#include <set>#include <sstream>using namespace std;#define read() freopen("data.in", "r", stdin)int main(){//read();ostringstream a("hello");cout<<a.str()<<endl;a.put(‘2‘);cout<<a.str()<<endl;a.put(‘233‘);cout<<a.str()<<endl;return 0;}
stringstream類
支援<<, >>操作符,可以進行字串到其它類型的快速轉換
應用: 字串與其他資料類型的轉換
#include <iostream>#include <algorithm>#include <cstdlib>#include <cstdio>#include <string>#include <cstring>#include <cmath>#include <ctime>#include <set>#include <sstream>using namespace std;#define read() freopen("data.in", "r", stdin)int main(){//read();//浮點型變成字串double a = 233.233;string str1;string str2;stringstream b;b << a;b >> str1;cout<<str1<<endl;b.clear();//多次使用stringstream,要先清空下,不能使用stream.str("");否則下面輸出10 //char變stringchar str[10] = "hello";b << str;b >> str2;cout<<str2<<endl;b.clear(); //string變int string str3 = "123"; int c; b << str3; b >> c; cout<<c<<endl; //可以用sizeof(c)看一下,c已經變成了4個位元組的整形啦。return 0;}
參考文章:http://www.cnblogs.com/gamesky/archive/2013/01/09/2852356.html
C++的輸入輸出資料流簡單總結【字串】