将无符号long long转换为wchar_t *并连接

时间:2016-07-28 15:19:24

标签: c++ windows winapi visual-c++ visual-studio-2015

关于这个问题有很多问题,我一直在尝试各种解决方案。似乎有很多方法可以做到这一点,但它们都没有工作。我是C ++和VS的新手,工作了大约一个月,我正在尝试使用VC ++编写自动Excel程序。我试图连接wchar_t *和unsigned long long。我假设第一步是"转换" unsigned long long to wchar_t *。我为抛出整个代码而道歉,但我认为它可能有助于展示我的目标以及代码中是否存在任何其他弱点。

wchar_t * ex(wchar_t * dest, unsigned long long num);
int main()
{

unsigned long long num = 10;
wchar_t *dest= L"A2:B";
wchar_t * Path=ex(dest, num);
VARIANT param;
    param.vt = VT_BSTR;
//      param.bstrVal = SysAllocString(L"A2:B10");
    param.bstrVal = SysAllocString(Path);
getchar();

return 0;
}

wchar_t * ex(wchar_t * dest, unsigned long long num)
{
    // Convert num to wchar_t *
    wchar_t *rangeMax = (wchar_t *)num;

    // I think this is used to eliminate extra space in other solutions
    // but not here. It could be useful.
    const int MAX_CHARS = 50;
    size_t count = wcsnlen_s(dest, MAX_CHARS);
    wprintf(L"The length of the string is %ld characters\n", count);

    // Throw dest into buf
    wchar_t buf[25] = { 0 };
    int r = wcscpy_s(buf, 25, dest);
    if (r != 0) {
        wprintf(L"wcscpy_s() failed %ld", r);
    }

    r = wcscat_s(buf, 25, rangeMax);

    if (r != 0) {
        wprintf(L"wcscat_s() failed %ld", r);
    }
    wprintf_s(buf);
    return buf;
}

ex是来自zetcode的编辑示例。我认为它接近于解决方案,但是当组合buf和rangeMax时,代码会抛出各种内存异常并失败。

正如您所看到的,连接的wchar_t *的最终目的地是通过SysAllocString在VARIANT中作为BSTR。

我感谢有关代码改进的任何建议以及如何使代码实际运行!

1 个答案:

答案 0 :(得分:0)

正如建议的那样使用wstring按预期运行。谢谢你指出我正在返回一个指向局部变量的指针!回到main后,类型被更改为wchar_t *,它很好地传递给SysAllocString()以供我的主程序使用。

std::wstring ex(wchar_t * dest, unsigned long long num);
int main()
{
    unsigned long long num = 10;
    wchar_t *dest= L"A2:B";
    std::wstring PathString= ex(dest, num);
    wchar_t *wPath = (WCHAR *)PathString.c_str();
    std::wcout << L"In main\n";
    std::wcout << wPath << L'\n';
    VARIANT param;
        param.vt = VT_BSTR;
        //param.bstrVal = SysAllocString(L"A2:B10");
        param.bstrVal = SysAllocString(wPath);

getchar();

return 0;
}

std::wstring ex(wchar_t * dest, unsigned long long num)
{
    std::wstring rangeMax = std::to_wstring(num);
    std::wstring string(dest);
    string += rangeMax;
    std::wcout << L"In function\n";
    std::wcout<<string<<L'\n';

    return string;
}