【问题标题】:Default integer'image() width in AdaAda 中的默认 integer'image() 宽度
【发布时间】:2011-10-15 13:31:21
【问题描述】:

如何更改 Ada 中默认的 integer'image() 宽度?

我希望能够执行 put("this is a number: " & i'img); 之类的操作,其中 i 为例如 5,并且让 Ada 输出没有多余空格的数字..

目前我必须做put("this is a number: "); put(i, 0);...

有没有办法解决这个问题?

顺便说一句,我知道 X'img 是一个 gnat 扩展 :)

【问题讨论】:

标签: image integer width ada


【解决方案1】:

尝试类似:

Package K is
    Type New_Type is New Integer;
private
  Function Image( Item : In New_Type ) Return String;
End K;

Package Body K is
  Use Ada.Text_IO;

  Function Image( Item : In New_Type ) Return String is
    begin
        Return ("This is a number: " &  Integer'Image(Integer(Item)) );
        -- You could also add a local integer variable, say Integer_Value,
        -- initialized to Integer(Item) and then use Integer_Value'Img.
    end Image;
End K;

【讨论】:

  • Use Ada.Text_IO; 是干什么用的?
  • Ada.Text_IO 是用于文本输入和输出功能的预定义包;它包含在 Image 函数示例中使用的 Put_Line。
  • 哦!大声笑——我用它来测试'图像......包K在一个声明K.New_Type变量的过程中;我想我在验证它按预期工作后忘记删除它。
【解决方案2】:

您现在的操作方式提供了最大的灵活性;使用'Image 或'Img 总是包含一个空格代表正值,一个“-”代表负值。 §A.10.8 Input-Output for Integer Types 显示通用包Ada.Text_IO.Integer_IO 中可用的Put 过程。你可以自己实例化它:

package Ada.Integer_Text_IO is new Ada.Text_IO.Integer_IO(Integer);

或者,您可以使用标准规定的预定义实例;重命名可能很方便:

with Ada.Integer_Text_IO;
package Int_IO renames Ada.Integer_Text_IO;

为方便起见,您可以定义一个返回String 的函数并将其与String concatenation operator, & 一起使用。

【讨论】:

  • @oenone: 'Image 经常出现在Ada.Calendar.Formatting 和Ada.Text_IO.Editing 等包的实现中。你能详细说明一下吗?
【解决方案3】:

只写自己的图像函数?

function Image (X : in Integer) return String is
    Img : constant String := Integer'Image (X);
begin
    if X < 0 then
        return Img;
    else
        return Img (2 .. Img'Length);
    end if;
end Image;

那么你就可以走了:

put("this is a number: " & Image (i));

【讨论】:

    【解决方案4】:

    function Img (X: Integer) 返回字符串为 (Ada.Strings.Fixed.Trim (X'Img, Ada.Strings.Both));

    【讨论】:

      猜你喜欢
      • 2010-12-23
      • 2011-08-17
      • 2014-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-19
      相关资源
      最近更新 更多