問題描述
我嘗試過實現這樣的功能,但不幸的是它不起作用:
I've tried implementing a function like this, but unfortunately it doesn't work:
const wchar_t *GetWC(const char *c)
{
const size_t cSize = strlen(c)+1;
wchar_t wc[cSize];
mbstowcs (wc, c, cSize);
return wc;
}
我的主要目標是能夠在 Unicode 應用程序中集成普通字符字符串.非常感謝你們提供的任何建議.
My main goal here is to be able to integrate normal char strings in a Unicode application. Any advice you guys can offer is greatly appreciated.
推薦答案
使用 std::wstring
而不是 C99 變長數組.當前標準保證 std::basic_string
的連續緩沖區.例如,
Use a std::wstring
instead of a C99 variable length array. The current standard guarantees a contiguous buffer for std::basic_string
. E.g.,
std::wstring wc( cSize, L'#' );
mbstowcs( &wc[0], c, cSize );
C++ 不支持 C99 可變長度數組,因此如果您將代碼編譯為純 C++,它甚至無法編譯.
C++ does not support C99 variable length arrays, and so if you compiled your code as pure C++, it would not even compile.
隨著更改,您的函數返回類型也應該是 std::wstring
.
With that change your function return type should also be std::wstring
.
記得在main
中設置相關的locale.
Remember to set relevant locale in main
.
例如,setlocale( LC_ALL, "" )
.
這篇關于如何將 char* 轉換為 wchar_t*?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!