StringCbPrintf 示例不工作

StringCbPrintf Example Not Working

在从 MSDN 构建示例时使用多字节字符集,我们得到最后一行的 "initializer is not a constant" 错误。 VS10 SP1,无 CLR。​​

        #define arraysize 30
        TCHAR pszDest[arraysize]; 
        size_t cbDest = arraysize * sizeof(TCHAR);

        LPCTSTR pszFormat = TEXT("%s %d + %d = %d.");
        TCHAR* pszTxt = TEXT("The answer is");

        HRESULT hr = StringCbPrintf(pszDest, cbDest, pszFormat, pszTxt, 1, 2, 3);

        // The resultant string at pszDest is "The answer is 1 + 2 = 3."

其他 CLR 选项失败。无论如何消除错误?

基于 C 的代码(即 Hans 的评论)可以在 VS Win32 项目中运行。模块范围的声明是:

#include <windows.h>
#include "stdafx.h"
#include <Strsafe.h> 
#include <stdio.h>
#include "msgbox.h"
int hr = 0;
#define arraysize 30
wchar_t hrtext[128];
HWND hWnd;

代码被插入到 _tWinMain 过程中:

    TCHAR pszDest[arraysize]; 
    size_t cbDest = arraysize * sizeof(TCHAR);

    LPCTSTR pszFormat = TEXT("%s %d + %d = %d.");
    TCHAR* pszTxt = TEXT("The answer is");

    HRESULT hr = StringCbPrintf(pszDest, cbDest, pszFormat, pszTxt, 1, 2, 3);

                if(hr == S_OK)
                {
                MessageBox(hWnd, pszDest, L"Information", MB_OK);

                }
                else
                {

                swprintf_s(hrtext, sizeof(hrtext), L"StringCbPrintf didn't work, quitting: code %#08X" , hr);

                MessageBox(hWnd, hrtext, L"Warning", MB_OK);
                }
    EndDialog(hWnd, 0);
    return FALSE;