c++ 整形轉換字串例子

來源:互聯網
上載者:User

第一種情況:輸出正常
#include <isotream>
#include <sstream>
#include <string>
using namespce std;
string intToString(int a)
{
 ostringstream ostr;
 ostr<<hex<<100;
 string str = ostr.str();
 cout<<str;
 return str;
}

第二種情況:輸出有亂碼
#include <isotream>
#include <sstream>
#include <string>
using namespce std;
string intToString(int a)
{
 ostrstream ostr;
 ostr<<hex<<100;
 string str = ostr.str();
 cout<<str;
 return str;
}
==========================================================================
ostrstream:是從ostream(輸出資料流類)和strstreambase(字串流基類)派生而來的
istrstream:是從istream(輸入資料流類)和strstreambase(字串流基類)派生而來的
strstream:是從iostream(輸入輸出資料流類)和strstreambase(字串流基類)派生而來的
istrstream類用於執行c風格的串流的輸入操作,也就是一字串數組作為輸入裝置
ostrstream類用於執行c風格的串流的輸入操作,也就是一字串數組作為輸入裝置
strstream類用於執行c風格的串流輸入輸出操作。
ostringstream 
istringstream

在c++有兩種字串流,一種是在 sstream中定義,一種是在strstream中定義,他們的實現基本都一樣。
strstream裡包含:
class strstrambuf;
class istrstream
class ostrstream;
class strstream;
他們是基於c字串char *編寫的。
sstream中包含:
class istringstream
class ostringstream
class stringbuf
class stringstream
他們是基於std::string編寫的
因此ostringstream::str()返回的是std::string類型的字串,ostrstream::str()返回的是char *類型的字串
在使用的時候要注意二者的區別。一般情況下推薦使用std::string類型的字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.