2

したがって、次のような関数があります。

std::string url_encode_wstring(const std::wstring &input)
     {
         std::string output;
         int cbNeeded = WideCharToMultiByte(CP_UTF8, 0, input.c_str(), -1, NULL, 0, NULL, NULL);
         if (cbNeeded > 0) {
             char *utf8 = new char[cbNeeded];
             if (WideCharToMultiByte(CP_UTF8, 0, input.c_str(), -1, utf8, cbNeeded, NULL, NULL) != 0) {
                 for (char *p = utf8; *p; *p++) {
                     char onehex[5];
                     _snprintf(onehex, sizeof(onehex), "%%%02.2X", (unsigned char)*p);
                     output.append(onehex);
                 }
             }
             delete[] utf8;
         }
         return output;
     }

Windows用の火格子ですが、Linuxで動作させるにはどうすればよいでしょうか(そして可能ですか)?

4

1 に答える 1

3

私見では、移植可能な文字コーデック ライブラリを使用する必要があります。以下は、iconv を使用した最小限の移植可能なコードの例です。これで十分です。Windows で動作するはずです (動作する場合は、Windows 固有のコードを完全に削除できます)。wcstombs & co 関数を使用しないように GNU ガイドラインに従います ( https://www.gnu.org/s/hello/manual/libc/iconv-Examples.html ) ユースケースに応じて、エラーを適切に処理します...パフォーマンスを向上させるために、そこからクラスを作成できます。

#include <iostream>

#include <iconv.h>
#include <cerrno>
#include <cstring>
#include <stdexcept>

std::string wstring_to_utf8_string(const std::wstring &input)
{
    size_t in_size = input.length() * sizeof(wchar_t);
    char * in_buf = (char*)input.data();
    size_t buf_size = input.length() * 6; // pessimistic: max UTF-8 char size
    char * buf = new char[buf_size];
    memset(buf, 0, buf_size);
    char * out_buf(buf);
    size_t out_size(buf_size);
    iconv_t conv_desc = iconv_open("UTF-8", "wchar_t");
    if (conv_desc == iconv_t(-1))
        throw std::runtime_error(std::string("Could not open iconv: ") + strerror(errno));
    size_t iconv_value = iconv(conv_desc, &in_buf, &in_size, &out_buf, &out_size);
    if (iconv_value == -1)
        throw std::runtime_error(std::string("When converting: ") + strerror(errno));
    int ret = iconv_close(conv_desc);
    if (ret != 0)
        throw std::runtime_error(std::string("Could not close iconv: ") + strerror(errno));
    std::string s(buf);
    delete [] buf;
    return s;
 }


int main() {
    std::wstring in(L"hello world");
    std::wcout << L"input: [" << in << L"]" << std::endl;
    std::string out(wstring_to_utf8_string(in));
    std::cerr << "output: [" << out << "]" << std::endl;
    return 0;
}
于 2011-10-01T20:55:48.897 に答える