【问题标题】:string to wstring - prevent conversion from stopping on \0字符串到 wstring - 防止转换停止在 \0
【发布时间】:2014-12-21 17:53:38
【问题描述】:

所以我有 string 变量,我想将其转换为 wstring

我正在使用mbstowcs_s

不幸的是,我的 string 变量包含 \0 作为一个字符(不标记字符串的结尾)并且已经记录:

mbstowcs_s 函数转换指向的多字节字符串 通过 mbstr 转换为存储在 wcstr 指向的缓冲区中的宽字符。 将继续为每个字符进行转换,直到满足以下条件之一: 遇到多字节空字符

我的临时解决方案是逐字符转换。这解决了这个问题,但不幸的是性能急剧下降。

知道如何克服这个问题吗?我必须使用不同的功能进行转换吗?

【问题讨论】:

标签: c++ c string type-conversion wstring


【解决方案1】:

您可以使用MultiByteToWideChar,它允许您指定要转换的字符数。

int MultiByteToWideChar(
  _In_       UINT CodePage,
  _In_       DWORD dwFlags,
  _In_       LPCSTR lpMultiByteStr,
  _In_       int cbMultiByte,
  _Out_opt_  LPWSTR lpWideCharStr,
  _In_       int cchWideChar
);

MultiByteToWideChar函数。

但是,MultiByteToWideChar 是 Win32 API,但在您的情况下应该没问题。

IIRC mbstowcs 也调用 MultiByteToWideChar

【讨论】:

  • 如果mbstowcs 也调用MultiByteToWideChar,他们是否故意调用MultiByteToWideChar 以停止在\0 上?
  • 如果您使用 cbMultiByte=-1 调用 MultiByteToWideChar,它也会在 \0 上停止,这就是 mbstowcs 可能会做的事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-13
  • 2021-11-21
  • 2014-02-01
  • 1970-01-01
相关资源
最近更新 更多