9

当我在下面打印此程序时 -

procedure put (Date:Date_Type) is
begin
  Put(Integer'Image(Date.Day)); --'
  Put("-");
  Put(Integer'Image(Date.Month)); --'
  Put("-");
  Put(Integer'Image(Date.Year)); --'
end;

结果是(例如):1- 1- 2010

我的问题是如何防止每个 Date 值之前有一个字符的间距。(日月年)。当然,我正在使用日期程序,并在持有日/月/年内记录。

提前致谢。

4

1 回答 1

14

你有几个选择:

  • 如果您知道整数值始终为非负数,则可以对字符串进行切片以省略前导空格。
  • 您可以使用 Ada.Strings.Fixed.Trim() 函数来修剪空白。
  • 您可以使用 Ada.Text_IO.Integer_IO 实例化(例如预实例化的 Ada.Integer_Text_IO)中的 Put() 过程。

这里有一些代码来说明:

with Ada.Text_IO;
with Ada.Integer_Text_IO;
with Ada.Strings.Fixed;

procedure Int_Image is

   use Ada.Text_IO;
   use Ada.Integer_Text_IO;
   use Ada.Strings.Fixed;

   N : Integer := 20;

   Raw_Image     : constant String := Integer'Image(N);

   Trimmed_Image : constant String := Trim(Raw_Image, Ada.Strings.Left);

   Sliced_Image  : constant String := Raw_Image(2 .. Raw_Image'Last);

begin
   Put_Line("Raw 'image    :" & Raw_Image & ":");
   Put_Line("Trimmed image :" & Trimmed_Image & ":");
   Put_Line("Sliced image  :" & Sliced_Image & ":");
   Put     ("'Put' image   :");
   Put     (N, Width => 0);
   Put_Line(":");
end Int_Image;

使用 GNAT 编译和运行它会产生:

$./int_image
Raw 'image    : 20:
Trimmed image :20:
Sliced image  :20:
'Put' image   :20:
于 2009-12-04T14:46:22.227 回答