C++ STD :: String到STD :: WSTRING -Windows vs Linux的转换问题

发布于 2025-02-10 02:24:32 字数 243 浏览 1 评论 0 原文

将字符串从std :: string转换为std :: string :: Wstring

我正在尝试使用 std :: Wstring wstmp(str.begin(),str.end()) ;

在Windows上起作用,但是在Linux上它返回“ POK \ XFFFFFC3 \ XFFFFFFFA9MON”

如何使其在Linux上工作?

I'm trying to convert the string "pokémon" from std::string to std::wstring using

std::wstring wsTmp(str.begin(), str.end());

This works on Windows, but on Linux it returns "pok\xffffffc3\xffffffa9mon"

How can I make it work on Linux?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

昔日梦未散 2025-02-17 02:24:32

这在Posix上对我有用。

#include <codecvt>
#include <string>
#include <locale>

int main() {
    
    std::string a = "pokémon";
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> cv;
    std::wstring wide = cv.from_bytes(a);
    
    return 0;
}

wstring 在末尾保持正确的字符串。

@nathanoliver的重要说明: std :: codecvt_utf8_utf16 在C ++ 17中弃用,并可以从未来版本的标准中删除。

This worked for me on POSIX.

#include <codecvt>
#include <string>
#include <locale>

int main() {
    
    std::string a = "pokémon";
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> cv;
    std::wstring wide = cv.from_bytes(a);
    
    return 0;
}

The wstring holds the correct string at the end.

Important note by @NathanOliver: std::codecvt_utf8_utf16 was deprecated in C++17 and may be removed from the standard in a future version.

熟人话多 2025-02-17 02:24:32

您似乎在这里遇到的问题是,它正在将é的两个代码单元视为转换时的单独代码点。使用C ++ 17的标准库是没有好的方法,因为 std :: Wstring_convert 被弃用而未得到适当的替换。您有几个选项,它们都不是很棒:

  1. 使用defted std :: wstring_convert ,而忽略了弃用警告,并且在将来的C ++修订版中可以将其删除。
  2. 实施自己的扩大转换例程(您可以使用为此提供帮助)。
  3. 使用一个较重的库,例如为您做所有繁重的举重。

同样有些无关,但是如果您关心跨不同平台的一致性,则应使用 std :: U16String std :: U32String std :: Wstring 的字符大小取决于 wchar_t 的大小,该大小在不同的编译器和平台之间变化。

The problem you seem to be running into here is that it's treating the é's two code units as separate code points when converting. There's no good way to do this with the standard library past C++17, as std::wstring_convert was deprecated without being given a proper replacement. You have several options, none of them great:

  1. Use the deprecated std::wstring_convert and ignore the deprecation warnings and the fact that it may be removed in a future revision of C++.
  2. Implement your own widening conversion routine (You could use icu4c's BreakIterator to assist with this).
  3. Use a heavier library like Boost.Locale to do all the heavy lifting for you.

Also somewhat unrelated, but if you care about consistency across different platforms you should be using std::u16string or std::u32string. std::wstring's character size depends on the size of wchar_t, which varies between different compilers and platforms.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文