流處理類:std::ostringstream, ostream, istream, iostream, fstream等


 

使用流處理進行字符串處理、文件的讀寫,比較方便,而且聽說效率也不錯(我還沒有研究過stl源碼)。

詳細可查閱:http://www.cplusplus.com/reference/istream/istream/


std::ostringstream用法淺析

轉自: http://www.cnblogs.com/520zijuan/archive/2013/02/16/2913736.html,文章很清晰,看着都很舒服,直接轉過來了。

ostringstream是C++的一個字符集操作模板類,定義在sstream.h頭文件中。ostringstream類通常用於執行C風格的串流的輸出操作,格式化字符串,避免申請大量的緩沖區,替代sprintf。

派生關系圖:

ios
ostringstream
 

ostringstream的構造函數形式:

1 explicit ostringstream ( openmode which = ios_base::out );
2 explicit ostringstream ( const string & str, openmode which = ios_base::out );

有時候,我們需要格式化一個字符串,但通常並不知道需要多大的緩沖區。為了保險常常申請大量的緩沖區以防止緩沖區過小造成字符串無法全部存儲。這時我們可以考慮使用ostringstream類,該類能夠根據內容自動分配內存,並且其對內存的管理也是相當的到位。

復制代碼
 1 #include <sstream>
 2 #include <string>
 3 #include <iostream>
 4 using namespace std;
 5 
 6 void main()
 7 {
 8     ostringstream ostr1; // 構造方式1
 9     ostringstream ostr2("abc");    // 構造方式2
10 
11 /*----------------------------------------------------------------------------
12 *** 方法str()將緩沖區的內容復制到一個string對象中,並返回
13 ----------------------------------------------------------------------------*/
14     ostr1 << "ostr1" << 2012 << endl;    // 格式化,此處endl也將格式化進ostr1中
15     cout << ostr1.str(); 
16 
17 /*----------------------------------------------------------------------------
18 *** 建議:在用put()方法時,先查看當前put pointer的值,防止誤寫
19 ----------------------------------------------------------------------------*/
20     long curPos = ostr2.tellp(); //返回當前插入的索引位置(即put pointer的值),從0開始 
21     cout << "curPos = " << curPos << endl;
22 
23     ostr2.seekp(2);    // 手動設置put pointer的值
24     ostr2.put('g');        // 在put pointer的位置上寫入'g',並將put pointer指向下一個字符位置
25     cout << ostr2.str() << endl;
26     
27 
28 /*----------------------------------------------------------------------------
29 *** 重復使用同一個ostringstream對象時,建議:
30 *** 1:調用clear()清除當前錯誤控制狀態,其原型為 void clear (iostate state=goodbit);
31 *** 2:調用str("")將緩沖區清零,清除臟數據
32 ----------------------------------------------------------------------------*/
33     ostr2.clear();
34     ostr2.str("");
35 
36     cout << ostr2.str() << endl;
37     ostr2.str("_def");
38     cout << ostr2.str() << endl;
39     ostr2 << "gggghh";    // 覆蓋原有的數據,並自動增加緩沖區
40     cout << ostr2.str() << endl;
41 }
復制代碼

詳細用法請參考如下網址:http://www.cplusplus.com/reference/sstream/ostringstream/

 


c++文件流基本用法(fstream, ifstream, ostream)

 可參考:http://blog.csdn.net/bichenggui/article/details/4600153,寫得也挺好的,只是內容太多,不轉過來了。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM