gpt4 book ai didi

c++ - 传递与 `swprintf` %s"` 说明符匹配的 `char const*` 时 `L"的行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:04:27 27 4
gpt4 key购买 nike

我正在编写一个 Excel 插件,需要生成 wchar_tExcel 的输出(尽管在内部,我们是 100% char,并且实际上将 char 限制为纯 ASCII)。有一次,我正在使用swprintf 进行转换:

static wchar_t buffer[ 32369 ];
buffer[0] = swprintf( buffer + 1, sizeof(buffer) - 1, L"#%s!", message );

Excel 显示某种 CJK 字符,尽管 message(type char const*) 是一个以 null 结尾的字符串没有可打印 ASCII 之外的字符(十六进制值 0x20-0x7E)。

我已经在一个小测试程序中尝试过,以十六进制转储生成的字符串,看起来 VC++ 正在处理 message就好像它是一个 wchar_t const* (虽然它看起来正确识别了 '\0',尽管它在单个字节);这导致 wchar_t 的值类似于 0x6568(而不是我期待的 0x0068, 0x0065)。

根据 C99 标准,对于 "%s" 说明符,swprintf 应该转换来自 char const* 的字符“就像通过重复调用 mbrtowc 函数 [...]”。是我看到的行为是 Visual C++ 库中的一个错误,或者我在全局语言环境中是否有什么东西改变?

(FWIW:当我用 g++ 编译和运行我的小测试程序时,我得到了我期望的行为。然而,G++ 不是我们的 Excel 插件,至少目前没有。)

最佳答案

请注意,来自 swprintf MSDN 的:

swprintf is a wide-character version of sprintf; the pointer arguments to swprintf are wide-character strings.

然后在示例中:

wchar_t buf[100];
int len = swprintf( buf, 100, L"%s", L"Hello world" );

所以至少 Microsoft 记录了这一点。

然后在format specifiers的页面中

s String When used with printf functions, specifies a single-byte–character string; when used with wprintf functions, specifies a wide-character string. Characters are printed up to the first null character or until the precision value is reached.

然后

S String When used with printf functions, specifies a wide-character string; when used with wprintf functions, specifies a single-byte–character string. Characters are printed up to the first null character or until the precision value is reached.

所以你想要的是大写的%S

甚至看到这个类似的问题:visual studio swprintf is making all my %s formatters want wchar_t * instead of char *他们建议使用 %ls(始终考虑参数 wchar_t*)和 %hs(始终考虑参数 char*)

关于c++ - 传递与 `swprintf` %s"` 说明符匹配的 `char const*` 时 `L"的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18715576/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com