WideFormat - C++ Builder

C++ Builder 参考手册System::SysutilsWideFormat


格式化输出到 WideString 类型的字符串

头文件:#include <System.SysUtils.hpp>
命名空间:System::Sysutils
函数原型:

System::WideString __fastcall WideFormat(
    const System::WideString Format,
    const System::TVarRec *Args,
    const int Args_High);

System::WideString __fastcall WideFormat(
    const System::WideString Format,
    const System::TVarRec *Args,
    const int Args_High,
    const TFormatSettings &AFormatSettings);

参数:

  • Format:格式字符串;
  • Args:要输出的数据;
  • Args_High:数据的个数减1;
  • AFormatSettings:地区格式;

返回值:

  • 按照参数 fmt 或 Format 的格式生成字符串,函数返回生成的字符串:
    格式和 <cstdio> 里面的 printf / sprintf 类似,不完全一样,详见函数 Format 的格式描述和表格;
    如果格式解析错误,会抛出 EConvertError 异常,而不是像 printf / sprintf 那样得到错误的结果;
    和 printf / sprintf 另一个不同:Format 函数使用地区格式,而 printf / sprintf 不使用地区格式;
  • 参数 Args, Args_High 可以使用 ARRAYOFCONST 宏,请参考本文后面的例子;
  • 地区格式的例子请参考 FloatToStrF
    如果有 AFormatSettings 参数,使用这个参数的格式;
    如果没有 AFormatSettings 参数,使用 全局变量 System::Sysutils::FormatSettings 作为地区格式;
  • 函数内部是通过调用函数 WideFmtStr 实现的,所以 WideFormat 和 WideFmtStr 函数执行结果相同,区别是通过参数返回输出结果,或通过函数返回值返回结果;
  • WideFormat 和 Format 的区别:参数和返回值类型不同:
    Format:参数和返回值是 UnicodeString 类型的;
    • WideFormat:参数和返回值是 WideString 类型的;
  • 没有 AFormatSettings 参数的函数不是线程安全的,因为使用了全局变量作为地区格式;带有 AFormatSettings 参数的函数是线程安全的。

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    int i = 123;
    double x = 4.5678;
    UnicodeString s = WideFormat(L"i=%d, x=%.3f", ARRAYOFCONST((i, x))); // 默认格式:当前地区 (中国)
    Memo1->Lines->Add(s); // i=123, x=4.568

    TFormatSettings fsFrench = TFormatSettings::Create(L"fr_FR"); // 法国格式
    s = WideFormat(L"i=%d, x=%.3f", ARRAYOFCONST((i, x)), fsFrench);
    Memo1->Lines->Add(s); // i=123, x=4.568

    TFormatSettings fsChinese = TFormatSettings::Create(L"zh_CN"); // 中国格式
    s = WideFormat(L"i=%d, x=%.3f", ARRAYOFCONST((i, x)), fsChinese);
    Memo1->Lines->Add(s); // i=123, x=4.568
}

运行结果:

运行结果

相关:


C++ Builder 参考手册System::SysutilsWideFormat

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容