cwinapiwindows-10variadic-functionserror-reporting

How do I pass va_list to wsprintfW()?


I'm trying to make a custom printf-like function that take the arguments, format then display on MessageBox but wsprintfW isn't working properly, it display some chinese characters, I think the encoding messed up somewhere but I can't see where. How to fix that?

the code:

void panic(const wchar_t *fmt, ...)
{
    wchar_t buffer[1024];
    va_list args = NULL;
    va_start(args, fmt);
    wsprintfW(buffer, fmt, args);
    va_end(args);
    MessageBoxW(NULL, buffer, L"error", MB_OK | MB_ICONERROR);
    ExitProcess(EXIT_FAILURE);
}

calling from:

panic(L"hello, %s!", L"michael");

return error:

enter image description here


Solution

  • You need to use the wvsprintfW function. (Note the "v" second letter in the function name.)

    void panic(const wchar_t *fmt, ...)
    {
        wchar_t buffer[1024];
        va_list args = NULL;
        va_start(args, fmt);
        wvsprintfW(buffer, fmt, args);
        va_end(args);
        MessageBoxW(NULL, buffer, L"error", MB_OK | MB_ICONERROR);
        ExitProcess(EXIT_FAILURE);
    }