将 STL unicode 字符串转换为 wxString 会给出空字符串

Converting STL unicode string to wxString gives empty string

本文关键字:字符串 wxString STL unicode 转换      更新时间:2023-10-16

我的代码是:

#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";
}
我希望结果是"6/6

",但我得到的是"6/0"。也就是说,b 为空。我做错了什么?

我尝试过其他转换,但它们也不起作用。

编译者:

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

wx 版本是 3.0.0.0. gcc 版本 4.9.2 20141101 (Red Hat 4.9.2-1) (GCC)。

默认情况下wxString使用当前语言环境来解释其输入,对于您的程序,此语言环境是默认的"C",因为您永远不会更改它。将其设置为与源文件使用的编码相对应的区域设置,以允许代码按预期编写的方式工作。

两个更好的选择是:

  1. 使用std::wstring = L"..." .
  2. 如果您确信源始终采用 UTF-8,请使用 wxString::FromUTF8("...")