developer
developer

Reputation: 678

_vsnwprintf_s not working as desired

Writing a module to convert the unnamed argument list to string output is not as desired.

void FormatOutput(wchar_t* formatstring, ...)
{
    wchar_t buffer[1024];
    memset(buffer, 0, sizeof(buffer));
    size_t size = lstrlenW(formatstring);
    va_list args;
    va_start(args, formatstring);
    size = _vsnwprintf_s(buffer, _countof(buffer), _TRUNCATE, formatstring, args);
    buffer[size] = L'\0';
    if (size < 0)
        __debugbreak();
    printf("size: %d, buff: %ls\n", size, buffer);
}

Invoking the module as below

FormatOutput(L"%s %d %d %f %c", "34", 23,34,10.23,'c');

Output:

size: 19, buff :

What is missing in the implementation ?

Upvotes: 1

Views: 1638

Answers (2)

developer
developer

Reputation: 678

The required change is to use L"34" while invoking the module

FormatOutput(L"%s %d %d %f %c", L"34", 23,34,10.23,'c');

Output

size: 20, buff: 34 23 34 10.230000 c

Upvotes: 0

user4815162342
user4815162342

Reputation: 155216

You are using the %s format and sending a single-byte character string argument in your call to FormatOutput and then to _vsnwprintf_s. Being a wide-character function, _vsnwprintf_s treats %s as synonymous to %ls and expects a wide string argument.

To resolve the issue, switch to the %hs format, or pass the wide string literal L"34". The same goes for %c and c, where you need to use %hc or pass L'c' as argument.

Upvotes: 3

Related Questions