繁体   English   中英

Ada语言 - 如何存储函数返回的字符串值?

[英]Ada language - How to store a string value returned by a function?

我正在尝试在Ada 2012中进行一些基本的命令行交互,但我找不到捕获从Ada.Command_Line.Command_Name()函数返回的字符串的方法。

我在网上找到的所有例子都只是使用Put()打印String而不先将其存储在局部变量中。 这是我尝试过的错误代码,当我尝试将返回String值分配给String变量时,它会编译但抛出CONSTRAINT_ERROR ... length check failed ...

with Ada.Command_Line; use Ada.Command_Line;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;

procedure Command_Line_Test is
  ArgC : Natural := 0;
  InvocationName : String (1 .. 80);
begin
  ArgC := Argument_Count;
  Put ("Number of arguments provided: ");
  Put (ArgC'Image);
  New_Line;

  InvocationName := Command_Name;  --  CONSTRAINT_ERROR here
  Put ("Name that the executable was invoked by: ");
  Put (InvocationName);
  New_Line;

end Command_Line_Test;

我只是使用Command_Name作为示例,但想象它是任何其他函数可以返回一个字符串(也许是一个在程序生命期间会多次改变的字符串),我们应该如何声明局部变量以存储返回的串?

Ada中的字符串处理与其他编程语言非常不同,当您声明一个String(1..80)时,它期望函数返回的字符串实际上具有长度1..80而您的可执行路径(由Command_Name返回)可能会更短(或更长)。

您可能总是引入新的声明块并在其中创建一个String变量,就像这里一样

with Ada.Command_Line; use Ada.Command_Line;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;

procedure Main is
   ArgC : Natural := 0;

begin
   ArgC := Argument_Count;
   Put ("Number of arguments provided: ");
   Put (ArgC'Image);
   New_Line;
   declare
      InvocationName: String := Command_Name;  --  no more CONSTRAINT_ERROR here
   begin
      Put ("Name that the executable was invoked by: ");
      Put (InvocationName);
      New_Line;
   end;

end Main;

或者您可以使用Ada.Strings.Unbounded包

with Ada.Command_Line; use Ada.Command_Line;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;

procedure Main is
   ArgC : Natural := 0;
   InvocationName : Unbounded_String;
begin
   ArgC := Argument_Count;
   Put ("Number of arguments provided: ");
   Put (ArgC'Image);
   New_Line;

   InvocationName := To_Unbounded_String(Command_Name);  --  no more CONSTRAINT_ERROR here

   Put ("Name that the executable was invoked by: ");
   Put (To_String(InvocationName));
   New_Line;

end Main;

同意Timur,除了不需要将Invocation_Name的声明移动到嵌套的声明块中。

你本来可以写的;

   Invocation_Name : String := Command;

它在原始代码中的位置,在程序Main的声明中。

还是更好;

   Invocation_Name : constant String := Command;

或者更好的是,完全取消声明并替换Main的最后3行;

   Put_Line ("Name that the executable was invoked by: " & Command);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM