Ada 支持 put_line 中的变量吗?

Kri*_*ian 2 ada objective-c

Ada 是否支持类似于字符串中的 Obj-C 变量的内容?

NSLog(@"This is text, here's a variable %f", floatvar);

我想写出漂亮的单行代码,例如:
put_line("The answer is %v", answer);

代替

put_line("The answer is ");
put(answer);

Ada*_*ght 5

您可能喜欢 Ada 常见问题解答,特别是第 9.9 部分。为了完整起见,我在这里引用它:

虽然标准包 Text_IO 提供了许多功能,但
对类似 printf 的函数的请求并不罕见。

(基于塔克塔夫脱建议的解决方案)

可以通过重载“&”操作符来获取一个 Format 类型的对象和一个某种类型的对象,并在执行适当的输出后返回 Format,适当地推进,从而产生类似 printf 的功能。剩余的格式可以转换回字符串——例如检查格式字符串末尾剩下的内容——或者简单地打印以显示末尾剩余的内容。例如:

 with Text_IO;
 package Formatted_Output is
   type Format is
     limited private;

   function Fmt (Str : String)
     return Format;

   function "&" (Left : Format; Right : Integer)
     return Format;
   function "&" (Left : Format; Right : Float)
     return Format;
   function "&" (Left : Format; Right : String)
     return Format;
   ... -- other overloadings of "&"

   procedure Print (Fmt : Format);

   function To_String (Fmt : Format)
     return String;

 private
   ...
 end Formatted_Output;

 with Formatted_Output; use Formatted_Output;
 procedure Test is
   X, Y : Float;
 begin
   Print (Fmt("%d * %d = %d\n") & X & Y & X*Y);
 end Test;
Run Code Online (Sandbox Code Playgroud)

Formatted_Output 的私有部分和正文留给读者作为练习;-)。

如果需要,可以将“File : File_Type”参数添加到 Fmt 的重载中(以创建类似于 fprintf 的内容)。

此功能类似于
C++的“<<”流运算符提供的功能。