开发者

Default integer'image() width in Ada

How can I change the default integer'image() width in Ada?

I'd like to be able to do things lik开发者_如何学Goe put("this is a number: " & i'img); with i being for example 5 and having Ada output the number without excess spaces..

Currently I have to do put("this is a number: "); put(i, 0);...

Is there any way around this?

Btw, I know X'imgis a gnat extension :)


Try something like:

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;


The way way you're doing it now provides the most flexibility; using 'Image or 'Img always includes a space for positive values and a "–" for negative values. §A.10.8 Input-Output for Integer Types shows the Put procedures available in the generic package Ada.Text_IO.Integer_IO. You can instantiate it yourself:

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

Alternatively, you can use a predefined instance, prescribed by the standard; a renaming may be convenient:

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

For convenience, you can define a function that returns String and use it with the String concatenation operator, &.


function Img (X: Integer) return String is (Ada.Strings.Fixed.Trim (X'Img, Ada.Strings.Both));


Just write your own image function?

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;

then you can just go:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜