gpt4 book ai didi

c++ - printf ("%s")、printf ("%ls")、wprintf ("%s") 和 wprintf ("%ls") 之间有什么区别?

转载 作者:IT老高 更新时间:2023-10-28 22:28:45 26 4
gpt4 key购买 nike

考虑这个示例程序:

#include <cstdio>
#include <cwchar>
#include <string>

int main()
{
std::string narrowstr = "narrow";
std::wstring widestr = L"wide";
printf("1 %s \n", narrowstr.c_str());
printf("2 %ls \n", widestr.c_str());
wprintf(L"3 %s \n", narrowstr.c_str());
wprintf(L"4 %ls \n", widestr.c_str());

return 0;
}

这个的输出是:

1 narrow 
2 wide

我想知道:

  1. 为什么不打印 3 和 4?
  2. 1 & 3 和 2 & 4 有什么区别?
  3. 如果 narrowstr 是 UTF8 而 widestr 是 UTF16 会有什么不同吗?

最佳答案

你需要做的:

wprintf(L"3 %hs \n", narrowstr.c_str());
wprintf(L"4 %s \n", widestr.c_str());

为什么?因为对于 printf%s 表示窄字符字符串。对于 wprintf%ls 表示宽。

但是,对于 wprintf%s 意味着宽,%ls 本身意味着宽。 %hs 意味着狭窄(两者都适用)。对于 printf%s,这种方式仅表示 %hs

在 VC++/Windows 上,%S(大写 S)会反转效果。因此 printf("%S") 表示宽,而 wprintf("%S") 表示窄。这对 _tprintf 很有用。

关于c++ - printf ("%s")、printf ("%ls")、wprintf ("%s") 和 wprintf ("%ls") 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26816547/

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