针对这种特定格式设置,有辅助工具可用。
procedure Put(Item : in Num; Width : in Field := Default_Width; Base : in Number_Base := Default_Base);
将一个带有Item
的字段对齐到右侧,并使用空白字符填充。其中Width
是字段宽度,Base
默认为10。
function Head (Source : in String; Count : in Natural; Pad : in Character := Space) return String;
function Tail (Source : in String; Count : in Natural; Pad : in Character := Space) return String;
返回格式化的字符串。其中
Count
是字段宽度,
Pad
是填充字段的内容。
Head
将字符串左对齐。
Tail
将字符串右对齐。
请使用8个字符长的列宽,并使用破折号作为填充字符。
Put_Line (Head ("Ashley", 8, '-'));
Put_Line (Head ("Aloha", 8, '-'));
Put_Line (Head ("Jack", 8, '-'));
Put_Line (Tail ("Ashley", 8, '-'));
Put_Line (Tail ("Aloha", 8, '-'));
Put_Line (Tail ("Jack", 8, '-'));
输出
Ashley--
Aloha---
Jack----
--Ashley
---Aloha
----Jack
属性 discrete_type'Width
返回一个长度,该离散类型需要以文本形式表示。
示例
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Float_Text_IO; use Ada.Float_Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
with Ada.Calendar; use Ada.Calendar;
procedure Test is
subtype Index is Positive range 95 .. 1223;
procedure Put_Line ( I : in out Index; Name : String; Phone : Natural; Address : String; T : in out Time ) is
begin
Put (I, Index'Width);
Put (": ");
Put (Head (Name, 10, ' '));
Put (" | ");
Put (Tail (Phone'Img (Phone'Img'First + 1 .. Phone'Img'Last), 13, '0'));
Put (" | ");
Put (Head (Address, 20, ' '));
Put (Year (T), Year_Number'Width);
Put ("-");
Put (Month (T), Month_Number'Width);
Put ("-");
Put (Day (T), Day_Number'Width);
I := Positive'Succ (I);
T := T + Duration (60 * 60 * 24 * 3);
New_Line;
end;
I : Index := Index'First;
Now : Time := Clock;
begin
Put_Line (I, "Ashley", 1033438392, "Wellington, New Zealand", Now);
Put_Line (I, "Aloha", 01087651234, "Hawaii, United States of America", Now);
Put_Line (I, "Jack", 01082840184, "Beijing, China", Now);
I := Index'Last - 3;
Put_Line (I,"Ashley", 1033438392, "Wellington, New Zealand", Now);
Put_Line (I,"Aloha", 01087651234, "Hawaii, United States of America", Now);
Put_Line (I,"Jack", 01082840184, "Beijing, China", Now);
end;
输出
95: Ashley | 0001033438392 | Wellington, New Zeal 2015- 5- 24
96: Aloha | 0001087651234 | Hawaii, United State 2015- 5- 27
97: Jack | 0001082840184 | Beijing, China 2015- 5- 30
1220: Ashley | 0001033438392 | Wellington, New Zeal 2015- 6- 2
1221: Aloha | 0001087651234 | Hawaii, United State 2015- 6- 5
1222: Jack | 0001082840184 | Beijing, China 2015- 6- 8
我建议创建一个用于电话号码的类型,我不确定它应该是带有前导零的字符串还是数字,电话号码的长度可能不同。
printf
更安全的方式执行此类操作。这可能是某人的一个不错的小项目... - T.E.D.