c - 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?
解决方案
只需使用旨在处理或打印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
.
推荐阅读
- ansible - 有没有办法在集群中克隆服务配置?
- python - 在 Raspberry Pi 和 Python 上流式传输 YouTube 播放列表
- java - 来自带有 Jewel/Topaz512 NFC 标签的 ACR122U 阅读器的“超时,目标尚未回答”
- javascript - 工作出色后,今天 Font Awesome 停止加载。网络::ERR_CERT_COMMON_NAME_INVALID
- javascript - 如何在我的 html 网站上显示每 10 分钟更新一次的文本文件?
- jetty - 从码头中的 ResourceHandler 访问会话
- python - 如何从 64 位创建 32 位版本的 Python 代码
- html - URL 编码 CSS 参数
- javascript - 如何在工作箱或 sw 中强制缓存文件?
- javascript - 查找 a 标签后的所有 jquery 输入字段