首页 > 解决方案 > Using sprintf_s with wchar does not format as expected

问题描述

I'm trying to create a new string, using sprintf_s from a WCHAR. My code looks like:

#include <stdio.h>
#include <Windows.h>
void main(int argc, char ** argv) {
    TCHAR header[200];
    TCHAR* uuid = L"4facda65-5b27-4c70-b7d4-58c57b87682a";
    sprintf_s(&header, 200, "Client-ID: %ws\n", uuid);
    printf("UUID: %ws\n", uuid);
    printf("Header: %ws\n", header);
}

How come header is printed as Header: and not as Header: 4facda65-5b27-4c70-b7d4-58c57b87682a.

I just can't seem to figure out what I'm doing wrong.

EDIT: Tim Randall's link helped me on my way to a solution that works. Replacing the sprintf_s line with swprintf(header, sizeof(header) / sizeof(*header), L"Client-ID: %ws\n", uuid); seems to work.

Still, I'm unsure why this works, and why sprintf_s didn't?

标签: cwinapi

解决方案


只需使用旨在处理或打印wchar_t字符串和明确定义的宽字符串的函数:

WCHAR header[200];
WCHAR* uuid = L"4facda65-5b27-4c70-b7d4-58c57b87682a";
swprintf_s(header, 200, L"Client-ID: %s\n", uuid);
wprintf(L"UUID: %s\n", uuid);
wprintf(L"Header: %s\n", header);

另请参阅:TCHAR 仍然相关吗?

另请注意,您只是header作为要写入的字符串传递,而不是&header.


推荐阅读