gpt4 book ai didi

c++ - wcscpy_s 不影响 wchar_t*

转载 作者:行者123 更新时间:2023-11-28 06:49:19 25 4
gpt4 key购买 nike

我正在尝试将一些字符串从数据库加载到结构中,但我一直遇到一个奇怪的问题。使用我的结构数据,

struct datum {
wchar_t* name;
wchar_t* lore;
};

我尝试了以下代码片段

datum thisDatum;
size_t len = 0;
wchar_t wBuffer[2048];

mbstowcs_s(&len, wBuffer, (const char*)sqlite3_column_text(pStmt, 1), 2048);
if (len) {
thisDatum.name = new wchar_t[len + 1];
wcscpy_s(thisDatum.name, len + 1, wBuffer);
} else thisDatum.name = 0;

mbstowcs_s(&len, wBuffer, (const char*)sqlite3_column_text(pStmt, 2), 2048);
if (len) {
thisDatum.lore = new wchar_t[len + 1];
wcscpy_s(thisDatum.lore, len + 1, wBuffer);
} else thisDatum.name = 0;

然而,虽然 thisDatum.name 复制正确,但 thisDatum.lore 总是垃圾,除了两次。如果项目是 Debug,一切都很好,但这不是一个选项。我还发现重写结构数据

struct datum {
wchar_t* lore;
wchar_t* name;
};

完全解决了 thisDatum.lore 的问题,但给我带来了 thisDatum.name 的垃圾。

最佳答案

尝试更像这样的东西:

struct datum {
wchar_t* name;
wchar_t* lore;
};

wchar_t* widen(const char *str)
{
wchar_t *wBuffer = NULL;
size_t len = strlen(str) + 1;
size_t wlen = 0;
mbstowcs_s(&wlen, NULL, 0, str, len);
if (wlen)
{
wBuffer = new wchar_t[wlen];
mbstowcs_s(NULL, wBuffer, wlen, str, len);
}
return wBuffer;
}

datum thisDatum;
thisDatum.name = widen((const char*)sqlite3_column_text(pStmt, 1));
thisDatum.lore = widen((const char*)sqlite3_column_text(pStmt, 2));
...
delete[] thisDatum.name;
delete[] thisDatum.lore;

也就是说,我会改用 std::wstring:

struct datum {
std::wstring name;
std::wstring lore;
};

#include <locale>
#include <codecvt>

std::wstring widen(const char *str)
{
std::wstring_convert< std::codecvt<wchar_t, char, std::mbstate_t> > conv;
return conv.from_bytes(str);
}

datum thisDatum;
thisDatum.name = widen((const char*)sqlite3_column_text(pStmt, 1));
thisDatum.lore = widen((const char*)sqlite3_column_text(pStmt, 2));

关于c++ - wcscpy_s 不影响 wchar_t*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24318483/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com