溫馨提示×

c++ urlencode如何避免亂碼

c++
小樊
84
2024-07-23 12:01:02
欄目: 編程語言

在C++中進行urlencode時,可以使用標準庫中的一些函數(shù)來避免亂碼。例如,可以使用std::stringstd::stringstream來構(gòu)建和處理URL編碼字符串。以下是一個示例代碼:

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>

std::string urlencode(const std::string &s) {
    std::ostringstream escaped;
    escaped.fill('0');
    escaped << std::hex;

    for (auto c : s) {
        if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
            escaped << c;
        } else if (c == ' ') {
            escaped << '+';
        } else {
            escaped << '%' << std::setw(2) << int((unsigned char)c);
        }
    }

    return escaped.str();
}

int main() {
    std::string input = "Hello, 世界";
    std::string encoded = urlencode(input);
    
    std::cout << "Encoded string: " << encoded << std::endl;
    
    return 0;
}

在上面的代碼中,urlencode函數(shù)將輸入的字符串進行URL編碼,并返回編碼后的字符串。通過使用std::ostringstreamstd::hex,可以確保輸出的URL編碼字符串不會出現(xiàn)亂碼。當然,還需要根據(jù)具體需求對特殊字符進行處理,確保生成的URL編碼字符串符合標準。

0