计算 Ada 中的新行
Counting new lines in Ada
我正在尝试编写一个高效的程序来计算标准输入中换行符的数量。我写了下面的程序:
with Ada.Text_IO;
procedure Main is
New_Lines : Integer := 0;
begin
while not Ada.Text_IO.End_Of_File loop
declare
Line : String := Ada.Text_IO.Get_Line;
begin
New_Lines := New_Lines + 1;
end;
end loop;
Ada.Text_IO.Put_Line (Integer'Image(New_Lines));
end Main;
如何提高效率?我注意到编译器警告不要使用 Line
。也许有一种方法可以指定我只对跳到换行符感兴趣?
您可以改用 Ada.Text_IO.Skip_Line
,以避免将行存储在堆栈中,并消除您提到的关于 Line
的警告。
您程序的修改版本:
with Ada.Text_IO;
procedure Main is
New_Lines : Integer := 0;
begin
while not Ada.Text_IO.End_Of_File loop
Ada.Text_IO.Skip_Line;
New_Lines := New_Lines + 1;
end loop;
Ada.Text_IO.Put_Line (Integer'Image(New_Lines));
end Main;
不过,这不能保证计入最后一行,除非 文件终止符 直接位于 行终止符 之前。 (虽然看起来至少GNAT会算)
请注意,在某些平台上,行终止符不仅仅是换行符,在windows上,它是CR+LF。
我正在尝试编写一个高效的程序来计算标准输入中换行符的数量。我写了下面的程序:
with Ada.Text_IO;
procedure Main is
New_Lines : Integer := 0;
begin
while not Ada.Text_IO.End_Of_File loop
declare
Line : String := Ada.Text_IO.Get_Line;
begin
New_Lines := New_Lines + 1;
end;
end loop;
Ada.Text_IO.Put_Line (Integer'Image(New_Lines));
end Main;
如何提高效率?我注意到编译器警告不要使用 Line
。也许有一种方法可以指定我只对跳到换行符感兴趣?
您可以改用 Ada.Text_IO.Skip_Line
,以避免将行存储在堆栈中,并消除您提到的关于 Line
的警告。
您程序的修改版本:
with Ada.Text_IO;
procedure Main is
New_Lines : Integer := 0;
begin
while not Ada.Text_IO.End_Of_File loop
Ada.Text_IO.Skip_Line;
New_Lines := New_Lines + 1;
end loop;
Ada.Text_IO.Put_Line (Integer'Image(New_Lines));
end Main;
不过,这不能保证计入最后一行,除非 文件终止符 直接位于 行终止符 之前。 (虽然看起来至少GNAT会算)
请注意,在某些平台上,行终止符不仅仅是换行符,在windows上,它是CR+LF。