【问题标题】:How to declare wchar_t and set its string value later on?如何声明 wchar_t 并稍后设置其字符串值?
【发布时间】:2013-10-04 22:30:35
【问题描述】:

我正在为 Windows 开发,我没有找到关于如何正确声明和稍后设置 unicode 字符串的足够信息。到目前为止,

wchar_t myString[1024] = L"My Test Unicode String!";

assume 上面所做的是 [1024] 是分配的字符串长度,即我需要在该字符串中拥有最大的字符数。 L"" 确保引号中的字符串是 unicode(我发现的一个 alt 是 _T())。现在稍后在我的程序中,当我尝试将该字符串设置为另一个值时,

myString = L"Another text";

我得到编译器错误,我做错了什么?

另外,如果有人有一个简单而深入的 unicode 应用程序资源,我想有一些链接,曾经为一个专门用于此的网站添加了书签,但现在似乎已经不存在了。

编辑

我提供了整个代码,我打算将其用作 DLL 函数,但到目前为止没有返回任何内容。

#include "dll.h"
#include <windows.h>
#include <string>
#include <cwchar>

export LPCSTR ex_test()
{
wchar_t myUString[1024];
std::wcsncpy(myUString, L"Another text", 1024);

int myUStringLength = lstrlenW(myUString);

MessageBoxW(NULL, (LPCWSTR)myUString, L"Test", MB_OK);

int bufferLength = WideCharToMultiByte(CP_UTF8, 0, myUString, myUStringLength, NULL, 0, NULL, NULL);
if (bufferLength <= 0) { return NULL; } //ERROR in WideCharToMultiByte
return NULL;

char *buffer = new char[bufferLength+1];
bufferLength = WideCharToMultiByte(CP_UTF8, 0, myUString, myUStringLength, buffer, bufferLength, NULL, NULL);
if (bufferLength <= 0) { delete[] buffer; return NULL; } //ERROR in WideCharToMultiByte

buffer[bufferLength] = 0;

return buffer;
}

【问题讨论】:

    标签: c++ string unicode wchar


    【解决方案1】:
    wchar_t myString[1024] = L"My Test Unicode String!";
    

    正在像这样初始化数组

    wchar_t myString[1024] = { 'M', 'y', ' ', ..., 'n', 'g', '!', '\0' };
    

    但是

    myString = L"Another text";
    

    是一个你不能对数组做的赋值。您必须将新字符串的内容复制到旧数组中:

    const auto& newstring = L"Another text";
    std::copy(std::begin(newstring), std::end(newstring), myString);
    

    或者如果它是一个指针

    wchar_t* newstring = L"Another text";
    std::copy(newstring, newstring + wsclen(newstring) + 1, myString);
    

    或如 nawaz 建议的 copy_n

    std::copy_n(newstring, wsclen(newstring) + 1, myString);
    

    【讨论】:

    • wchar_t (&amp;newstring)[] = L"Another text"; 不应编译。
    • @Nawaz 我想我修好了
    • 顺便说一句,对于最后一种情况:std::copy_n(newstring, wsclen(newstring)+1, myString); 读起来更好。
    【解决方案2】:

    最简单的方法是首先以不同的方式声明字符串:

    std::wstring myString;
    myString = L"Another text";
    

    如果您坚持直接使用wchar_t 的数组,您将使用wcscpy() 或更好的wcsncpy() from &lt;cwchar&gt;

    wchar_t myString[1024];
    std::wcsncpy(myString, L"Another text", 1024);
    

    【讨论】:

    • @Nawaz:我会让名字保持一致。 1024 是要复制的最大字符数。我看不出wcsncpy() 的使用方式是错误的。如果它使用wcscpy(),则有机会复制比空间更多的字符。
    • 是的,我已经验证过了。我不习惯 C 函数,因为我很少使用它们。 +1
    • wcscpy() 和 wcsncpy() 需要包含哪些标头?
    • @user780756:&lt;cwchar&gt;(带有std:: 前缀)和&lt;wchar.h&gt; 没有(我更新了答案)。
    • @user780756: std::wstring&lt;string&gt; 中声明。
    猜你喜欢
    • 2012-07-19
    • 2021-12-20
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    相关资源
    最近更新 更多