如何在windows和linux中使用相同的宽字符串格式

How to use same wide char string format for windows and linux

本文关键字:格式 字符串 windows linux      更新时间:2023-10-16

目前,我有一些代码将在Windows/Linux上运行。现在我在输出一些信息时遇到了一个问题
在windows上,我使用_vsnwprintf_s()来支持变量参数。所以它支持以下格式。

Log0(L"111");
Log1(L"%s", L"22");
Log2(L"%s, %d", L"33", 44);

在Linux上,我不能使用vswprintf来格式化字符串,但它需要使用%ls来格式化宽字符串。

Debug0(L"111");
Debug1(L"%ls", L"22");

目前,我想包装一个统一的函数InfoX()来支持跨平台,所以它内部会根据当前的操作系统类型使用LogX()或DebugX()
如您所见,在windows上,我将使用%s格式化宽字符串,但在linux上使用%ls。我不知道如何在在Info2()函数中。

Info2(L"???", L"22");

为什么不使用stl库?它是解决你问题的更好的工具。您使用宽字符,所以std::wstring是最好的解决方案。要创建"wstring"值,您可以使用"wstringstream",并且不需要格式化字符。

#include <sstream>
#include <iostream>
void LOG(std::wstring _sLog)
{
    std::wcout << _sLog << 'n';
    //Your LOG code
}
int main()
{
    std::wstringstream oss;
    std::wstring wideValue(L"my wide value :");
    oss << wideValue << 101;
    std::wstring s = oss.str();
    LOG(s);
    return 0;
}