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

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));

10-07 15:21