kro*_*mon 5 delphi printf delphi-2006
有没有人知道Delphi 的C/C++ printf的100%克隆?是的,我知道系统.格式化功能,但它处理的东西有点不同.
例如,如果要将3格式化为"003",则在C中需要"%03d",而在Delphi中需要"%.3d".
我有一个用Delphi编写的应用程序,它必须能够使用C格式字符串格式化数字,所以你知道一个代码片段/库吗?
提前致谢!
And*_*den 14
您可以使用Windows.pas中的wsprintf()函数.不幸的是,这个函数在Windows.pas中没有正确声明,所以这里是重新声明:
function wsprintf(Output: PChar; Format: PChar): Integer; cdecl; varargs;
external user32 name {$IFDEF UNICODE}'wsprintfW'{$ELSE}'wsprintfA'{$ENDIF};
procedure TForm1.FormCreate(Sender: TObject);
var
S: String;
begin
SetLength(S, 1024); // wsprintf can work only with max. 1024 characters
SetLength(S, wsprintf(PChar(S), '%s %03d', 'Hallo', 3));
end;
Run Code Online (Sandbox Code Playgroud)
如果你想让这个函数看起来对用户更友好,你可以使用以下代码:
function _FormatC(const Format: string): string; cdecl;
const
StackSlotSize = SizeOf(Pointer);
var
Args: va_list;
Buffer: array[0..1024] of Char;
begin
// va_start(Args, Format)
Args := va_list(PAnsiChar(@Format) + ((SizeOf(Format) + StackSlotSize - 1) and not (StackSlotSize - 1)));
SetString(Result, Buffer, wvsprintf(Buffer, PChar(Format), Args));
end;
const // allows us to use "varargs" in Delphi
FormatC: function(const Format: string): string; cdecl varargs = _FormatC;
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(FormatC('%s %03d', 'Hallo', 3));
end;
Run Code Online (Sandbox Code Playgroud)