溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++ tostring與字符串的編碼轉(zhuǎn)換

發(fā)布時(shí)間:2024-09-08 11:11:38 來源:億速云 閱讀:83 作者:小樊 欄目:編程語言

在 C++ 中,std::to_string() 函數(shù)用于將數(shù)字類型(如 int、float、double 等)轉(zhuǎn)換為字符串。然而,這個(gè)函數(shù)不涉及字符串編碼轉(zhuǎn)換,如 UTF-8、GBK 等。要進(jìn)行字符串編碼轉(zhuǎn)換,你需要使用第三方庫,如 Boost.Locale 或者 ICU 庫。

以下是一個(gè)使用 Boost.Locale 進(jìn)行字符串編碼轉(zhuǎn)換的示例:

#include<iostream>
#include<string>
#include<boost/locale.hpp>

int main() {
    std::string input = "你好,世界!";
    std::string output;

    // 創(chuàng)建一個(gè) Boost.Locale 轉(zhuǎn)換器
    boost::locale::generator gen;
    boost::locale::converter<char> conv(gen("zh_CN.UTF-8"));

    // 將 UTF-8 編碼的字符串轉(zhuǎn)換為 GBK 編碼
    try {
        output = conv.from_utf(input, "GBK");
    } catch (const boost::locale::conv::conversion_error &e) {
        std::cerr << "Error: " << e.what()<< std::endl;
        return 1;
    }

    std::cout << "Original string (UTF-8): "<< input<< std::endl;
    std::cout << "Converted string (GBK): "<< output<< std::endl;

    return 0;
}

在這個(gè)示例中,我們使用 Boost.Locale 庫將一個(gè) UTF-8 編碼的字符串轉(zhuǎn)換為 GBK 編碼。注意,你需要安裝并鏈接 Boost.Locale 庫才能使用這個(gè)代碼。

另外,如果你只是想將數(shù)字轉(zhuǎn)換為字符串,可以使用 std::to_string() 函數(shù)。以下是一個(gè)簡單的示例:

#include<iostream>
#include<string>

int main() {
    int num = 42;
    std::string str_num = std::to_string(num);

    std::cout << "Number: "<< num<< std::endl;
    std::cout << "String: "<< str_num<< std::endl;

    return 0;
}

這個(gè)示例將一個(gè)整數(shù)轉(zhuǎn)換為字符串。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI