C++: 對字串轉換字元集(編碼)

來源:互聯網
上載者:User

最近,linux上遇到string為漢字時,需要轉碼存入到資料庫中,將轉碼的函數及其方法記錄一下。

見函數:

 標頭檔是#include <iconv.h>

    //fromcode:源string使用的字元集,如"UTF-8";,對於漢字每個漢字為3個位元組儲存    //tocode:目的string使用的字元集,如"GB2312";,對於漢字每個漢字為2個位元組儲存    //in:需要轉碼的字串    //out:轉碼後的字串    int iconv_code(const string& fromcode, const string& tocode, const string& in, string& out)    {           char *sin, *sout;        size_t lenin, lenout;        int ret;        iconv_t c_pt;        if ((c_pt = iconv_open(tocode.c_str(), fromcode.c_str())) == (iconv_t)(-1)){            out=in;            return -1;        }                lenin = in.size()+1;//字串要有個結束符位        char* oldPasserName = new char[lenin];//這裡oldPasserName為工作中用的名字,沒什麼特殊含義        strcpy(oldPasserName, in.c_str());                lenout = lenin*10;        char* newPasserName = new char[lenout];        sin = oldPasserName;        sout = newPasserName;        ret = iconv(c_pt, &sin, &lenin, &sout, &lenout);        if(ret == -1){            out=in;            iconv_close(c_pt);            return -1;        }        iconv_close(c_pt);                out = newPasserName;        delete []oldPasserName;//別忘記釋放掉        delete []newPasserName;        return 0;    }

 

閑話:

       為什麼需要轉碼呢,一般情況下,資料庫使用GBK字元集儲存,而有使用UTF-8的字元集字串會傳入應用程式,這時容易發生問題,但假如應用程式環境變數是UTF-8的,資料庫如Oracle知道你傳的是UTF-8字串,它會自動幫你轉碼,這樣不會有問題;但環境變數標明是GBK的,而應用程式傳入UTF-8的漢字,那麼orale會儲存亂碼,因為你欺騙了oracle。所以出現“欺騙”的情形時需要轉碼,注意自己程式是否會欺騙資料庫。

        同時,這個iconv函數是作業系統自己開發的庫函數,而不是c++標準的,具體使用方式有可能依據系統不同而不同,我的環境是linux,所以各種linux發行版一般不會出現問題。
 

聯繫我們

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