C++中stringstream的使用方法和範例__C++

來源:互聯網
上載者:User

  之前在leetcode中進行string和int的轉化時使用過istringstream,現在大致總結一下用法和測試案例。  

  介紹:C++引入了ostringstream、istringstream、stringstream這三個類,要使用他們建立對象就必須包含sstream.h標頭檔。

istringstream類用於執行C++風格的串流的輸入操作。

ostringstream類用於執行C風格的串流的輸出操作。 

stringstream類同時可以支援C風格的串流的輸入輸出操作。

下圖詳細描述了幾種類之間的繼承關係:


istringstream是由一個string物件建構而來,從一個string對象讀取字元。  ostringstream同樣是有一個string物件建構而來,向一個string對象插入字元。 stringstream則是用於C++風格的字串的輸入輸出的。 
代碼測試:

#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}cout << "*********************" << endl;istringstream strm(test); //建立儲存 test 的副本的 stringstream 對象int i;float f;char c;char buff[1024];strm >> i;cout <<"讀取int類型:"<< i << endl;strm >> f;cout <<"讀取float類型:"<<f << endl;strm >> c;cout <<"讀取char類型:"<< c << endl;strm >> buff;cout <<"讀取buffer類型:"<< buff << endl;strm.ignore(100, ',');int j;strm >> j;cout <<"忽略‘,’讀取int類型:"<< j << endl;system("pause");return 0;}
 輸出: 總結: 1)在istringstream類中,構造字串流時,空格會成為字串參數的內部分界; 2)istringstream類可以用作string與各種類型的轉換途徑 3)ignore函數參數:需要讀取字串的最大長度,需要忽略的字元 代碼測試: 
int main(){ostringstream out;out.put('t');//插入字元out.put('e');out << "st";string res = out.str();//提取字串;cout << res << endl;system("pause");return 0;}
輸出:test字串; 註:如果一開始初始化ostringstream,例如ostringstream out("test"),那麼之後put或者<<時的字串會覆蓋原來的字元,超過的部分在原始基礎上增加。
stringstream同理,三類都可以用來字串和不同類型轉換。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.