我试图在Ada2012中进行一些基本的命令行交互,但我找不到一种方法来捕获从Ada.Command_Line.Command_Name()函数返回的字符串。
我在网上找到的所有示例只需使用Put()打印字符串,而无需首先将其存储在局部变量中。下面是我尝试过的错误代码,它可以编译,但当我试图将返回的字符串值赋给字符串变量时,它会抛出一个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作为示例,但是假设它是任何其他可以返回字符串(可能是在程序生命周期中多次更改的字符串)的函数,我们应该如何声明局部变量来存储返回的字符串?
发布于 2019-08-26 20:49:27
Ada中的字符串处理与其他编程语言非常不同,当您声明一个字符串( 1..80 )时,它期望函数返回的字符串实际长度为1..80,而您的可执行路径(由Command_Name返回)可能会更短(或更长)。
您可以随时引入新的declare块,并在其中创建一个字符串变量,如下所示
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;发布于 2019-08-26 22:47:23
同意Timur的观点,除了不需要将Invocation_Name的声明移动到嵌套的declare块中。
你可以直接写;
Invocation_Name : String := Command;它在原始代码中的位置,在过程Main的声明中。
或者更好;
Invocation_Name : constant String := Command;或者更好的是,完全删除声明,并将Main的最后3行替换为;
Put_Line ("Name that the executable was invoked by: " & Command);https://stackoverflow.com/questions/57657876
复制相似问题