Search code examples
c++c++11unicodestlwxwidgets

Converting STL unicode string to wxString gives empty string


My code is:

#include <string>
#include <iostream>
#include <wx/string.h>
int main(int n, char** c) {
    std::string a = "你好";
    wxString b = a;
    std::cerr <<a.length()<<"/"<< b.Len()<<"\n";
}

I would expect the result to be something like "6/6" but I am getting "6/0". That is, b is empty. What am I doing wrong?

I have tried other conversions but they do not work either.

Compiling by:

g++ `wx-config --cxxflags --libs` -std=c++11 -o string-test string-test.cpp

wx version is 3.0.0.0. gcc version 4.9.2 20141101 (Red Hat 4.9.2-1) (GCC).


Solution

  • wxString uses the current locale for interpreting its input by default and in case of your program this locale is the default "C" as you never change it. Set it to whichever locale corresponds to the encoding used by your source file to allow the code to work as expected as written.

    Two much better alternatives would be to:

    1. Use std::wstring = L"...".
    2. Use wxString::FromUTF8("...") if you are confident your sources are always in UTF-8.