Ada支持put_line中的变量?

时间:2012-01-24 20:50:40

标签: objective-c ada

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);

2 个答案:

答案 0 :(得分:4)

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

  

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

     

(根据Tucker Taft的建议提出的解决方案)

     

可以通过重载产生类似printf的功能   “&” operator用于获取Format类型的对象和   有些类型并返回格式,正确高级后,有   执行了适当的输出。剩下的格式可以是   转换回字符串 - 例如检查最后剩下的东西   格式字符串 - 或简单地打印以显示任何内容   仍然在最后。例如:

 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;
     

Formatted_Output的私有部分和正文保留为   为读者锻炼; - )。

     

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

     

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

答案 1 :(得分:3)

假设你有F : Float;,你可以说

Put_Line (“the answer is “ & Float’Image (F));

如果你想要整洁的格式,这不会很好,因为’Image输出的格式是固定的as specified in the ARM(该链接实际上是’Wide_Wide_Image,而不是’Image ,但格式相同)。

如果你正在使用GNAT,你可以将上面的内容写成

Put_Line (“the answer is “ & F'Img);

保存(a)字符和(b)记住相关类型,但这不是便携式的。