如何从Ada中的其他字符串构建字符串? [英] How to I build a string from other strings in Ada?

查看:105
本文介绍了如何从Ada中的其他字符串构建字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在日志文件中输出标题行,然后在数据之前输出-行。为此,我创建了标头的字符串,然后输出相同数量的'-'。

I want to output a header line in a log file and then a line of '-' before the data. To do this I create a string of the header and then outpout the same number of '-'.

但是以下代码始终失败,并显示CONSTRAINT_ERROR,因为生成的字符串是不是1024个字符。在Ada中,字符串分配需要完全相同的长度,而不仅仅是足够的容量。

But the below code always fails with a CONSTRAINT_ERROR because the generated string is not 1024 characters. In Ada string assignments require exactly the same length not just sufficient capacity.

选项1)用于计算确切的长度,但是这对于将来的更改很脆弱。
选项2)可以使用String以外的其他东西。

Option 1) is to compute the exact length but that is brittle to future changes. Option 2) is to use something other than String.

procedure F() is 
    Msg : String(1..1024);
begin
    Open_Log();
    Msg :=       FLS(" Field1", 12) &
           "|" & FLS(" Field2", 12) &
           "|" & FLS(" Field3", 16);

    Log_To_File("# " & Msg);
    Log_To_File("# " & Fill_String(Msg'Last, '-'));
end;


推荐答案

很多习惯C语言的人分步构建字符串的问题使他们无法专心于Ada字符串,您应该按原样初始化并使用。当您了解有关Ada字符串的事实时,解决方案变得更加简单。我什至可以扔掉您的填充例程。

A lot of folks who are used to the C way of building strings in steps have trouble wrapping their minds around Ada strings, which you are supposed to initialize and use as-is. When you grok this fact about Ada strings, the solution becomes much simpler. I can even throw out your "Fill" routine.

procedure F() is  
   Msg : constant String
      := FLS(" Field1", 12) & 
       "|" & FLS(" Field2", 12) & 
       "|" & FLS(" Field3", 16); 
   Separator : constant String := (1..Msg'length => '-'); --'
begin 
   Open_Log(); 

   Log_To_File("# " & Msg); 
   Log_To_File("# " & Separator); 
end;

(注意:此注释是使SO的着色剂重回正轨的一种手段)

(Note: The comment is a hack to get SO's colorizer back on track)

如果不必使分隔符具有相同的长度,则甚至不需要声明变量。

If you didn't have to have the separator the same length, you wouldn't even need to declare the variable.

如果是我,我会做一些事情,例如 Log_To_File 跟踪长度并正确生成自己的长度大小的分隔符根据要求。然后,您可以编写:

If it were me, I'd do something like have Log_To_File keep track of lengths and generate its own properly-sized separator upon request. Then you could just write:

Open_Log();
Log_To_File ("# " & FLS(" Field1", 12) & 
       "|" & FLS(" Field2", 12) & 
       "|" & FLS(" Field3", 16)); 
Log_Separator_To_File;

这篇关于如何从Ada中的其他字符串构建字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆