首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Ada语言-如何存储函数返回的字符串值?

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

Stack Overflow用户
提问于 2019-08-26 20:24:16
回答 2查看 645关注 0票数 7

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

我在网上找到的所有示例只需使用Put()打印字符串,而无需首先将其存储在局部变量中。下面是我尝试过的错误代码,它可以编译,但当我试图将返回的字符串值赋给字符串变量时,它会抛出一个CONSTRAINT_ERROR ... length check failed……

代码语言:javascript
复制
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作为示例,但是假设它是任何其他可以返回字符串(可能是在程序生命周期中多次更改的字符串)的函数,我们应该如何声明局部变量来存储返回的字符串?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-08-26 20:49:27

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

您可以随时引入新的declare块,并在其中创建一个字符串变量,如下所示

代码语言:javascript
复制
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包

代码语言:javascript
复制
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;
票数 10
EN

Stack Overflow用户

发布于 2019-08-26 22:47:23

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

你可以直接写;

代码语言:javascript
复制
   Invocation_Name : String := Command;

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

或者更好;

代码语言:javascript
复制
   Invocation_Name : constant String := Command;

或者更好的是,完全删除声明,并将Main的最后3行替换为;

代码语言:javascript
复制
   Put_Line ("Name that the executable was invoked by: " & Command);
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57657876

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档