【问题标题】:converting string to char * fails (codecvt)将字符串转换为 char * 失败(codecvt)
【发布时间】:2020-10-15 22:48:13
【问题描述】:

我有以下代码:

std::wstring my_string = L"foo";
std::wstring_convert<std::codecvt_utf8<wchar_t> > my_conv;
const char *chars = my_conv.to_bytes( my_string ).c_str();

转换返回一个空指针(不是NULL,只是"")。

to_bytes 是否返回一个临时指针? 如何正确编写这段代码?

【问题讨论】:

  • to_bytes 不返回指向 char 的指针。请发布minimal reproducible example。我不能reproduce这个。
  • @n.'pronouns'm。 '代词' m,我有 MSVC 2017 社区,在 Windows 8.1 上运行。你的环境是什么? it doesn't return a pointer to char 是什么意思?
  • 它返回 std::string。无论如何,这整个设施已被弃用。
  • @n.'pronouns'm.,它在什么标准中被弃用?以及如何将std::wstring 转换为char *?另外 - 我错过了c_str() 的电话。已添加。
  • @Igor std::wstring_convert 在 C++17 以后已弃用

标签: c++ c++11


【解决方案1】:

std::wstring_convert::to_bytes() 不返回临时指针。它返回一个临时的std::stringobject。您正在保存一个指向临时数据的指针,然后临时数据超出范围并随后被销毁,留下一个指向无效内存的悬空指针

保存std::string 本身,而不是指向其数据的char* 指针,例如:

std::wstring my_string = L"foo";
std::wstring_convert<std::codecvt_utf8<wchar_t> > my_conv;
std::string chars = my_conv.to_bytes( my_string );
// now use chars.c_str() when needed...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-27
    • 2013-05-13
    • 1970-01-01
    • 2020-09-30
    • 2014-05-16
    • 2012-01-16
    相关资源
    最近更新 更多