snprintf等效于WCHAR_T计算格式化的字符串大小(MAC)

snprintf equivalent for wchar_t to calculate formatted string size (mac)

本文关键字:字符串 MAC 格式化 计算 WCHAR snprintf      更新时间:2023-10-16

是否可以使用任何功能来计算与char_t(snprintf(类似的WCHAR_T格式的字符串大小?

MSVC具有SNWPRINTF,但我在Mac中找不到等效的。

如果没有

我在OSX(Apple LLVM版本8.0.0,Clang-800.0.42.1(和Centos(G 4.8.5 20150623红色帽子4.8.5-11(上尝试过此操作((Cubbi推荐的功能。

nb Mac上的swprintf((的人条目表示其返回值是"书面的字符数",而不是wchars的数量。

我运行了以下代码,并在每个平台上的注释中显示了输出结果:

#include <iostream>
#include <clocale>
#include <string>
#include <cstring>
int main()
{
    std::setlocale(LC_ALL, "en_US.utf8");
    char narrow_str[] = "zu00dfu6c34U0001f34c";
    std::cout << narrow_str << std::endl;                // zß水  
    std::cout << strlen(narrow_str) << std::endl;        // 10 (= 1 + 2 + 3 + 4)
    std::wstring wide_str = L"zu00dfu6c34U0001f34c";
    std::cout << wide_str.length() << std::endl;         // 4
    std::cout << wcslen(wide_str.c_str()) << std::endl;  // 4
    wchar_t warr[100];
    int n1 = std::swprintf(warr, sizeof warr/sizeof *warr, L"%s", narrow_str);
    int n2 = std::swprintf(warr, sizeof warr/sizeof *warr, L"Converted from UTF-8: '%s'", narrow_str);
    std::cout << n1 << std::endl;                        // 10 with LLVM, 4 with gcc
    std::cout << n2 << std::endl;                        // 34 with LLVM, 28 with gcc
}

从此看来,使用LLVM,(1(CPPReference上的原始代码失败并返回-1,因为WARR []数组太小,并且(2(以char中测量了来自swprintf((的返回值。

这可能会或可能没有帮助。