0

我的目标是从标准输入接收一个方程,将其存储在一个数组中以供以后使用/重新打印,然后输出一行打印整个方程和答案,就像这样:

输入:2+3=

输出:2 + 3 = 5

由于 Ada 无法拥有动态字符串等,我对如何执行此操作感到非常困惑。

这是我在伪代码中的一个粗略想法..

 Until_loop:                 
       loop 

         get(INT_VAR);
         --store the int in the array?
         get(OPERATOR_VAR);
         --store the operator in the following index of that array? and
         --repeat until we hit the equal sign, signaling end of the equation

         get(CHECK_FOR_EQUALSIGN);
     exit Until_loop when CHECK_FOR_EQUALSIGN = "=";

     end loop Until_loop;

 --now that the array is filled up with the equation, go through it and do the math
 --AND print out the equation itself with the answer

我猜数组应该是这样的:

[2][+][5][=][7]

我也是Ada的初学者,所以掌握起来更加困难,我对Java非常擅长,但是我不习惯强类型的语法。请询问您是否需要更多信息。

4

3 回答 3

3

Ada 可以使用动态固定字符串,而无需求助于 Unbounded_String 或容器,或者分配和指针,尽管这些是选项。

使这成为可能的见解是,字符串可以在声明时从其初始化表达式中获取其大小-但该声明可以在循环内,因此每次循环都重新执行它。你不能总是构建一个程序以使其有意义,尽管它经常令人惊讶地有可能,只需稍加思考即可。

另一个特点是,稍后,这些“声明”块非常适合轻松重构为过程。

with Ada.Text_IO; use Ada.Text_IO;

procedure Calculator is
begin
   loop
      Put("Enter expression: ");
      declare
         Expression : String := Get_Line;
      begin
         exit when Expression = "Done";
         -- here you can parse the string character by character
         for i in Expression'range loop
            put(Expression(i));
         end loop;
         New_Line;
      end;
   end Loop;
end Calculator;

你应该得到

brian@Gannet:~/Ada/Play$ gnatmake calculator.adb
gcc-4.9 -c calculator.adb
gnatbind -x calculator.ali
gnatlink calculator.ali
brian@Gannet:~/Ada/Play$ ./calculator
Enter expression: hello
hello
Enter expression: 2 + 2 =
2 + 2 =
Enter expression: Done
brian@Gannet:~/Ada/Play$ 

你还得写计算器……

于 2015-03-01T11:13:19.367 回答
1

如果您要做的只是输入一个可变长度的字符串,请将其提交给解析和评估字符串的评估器,然后将其与计算值一起反映回来,对于动态字符串处理,您可以简单地使用Unbounded_Strings无界_IO

with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Text_IO.Unbounded_IO; use Ada.Text_IO.Unbounded_IO;
use Ada.Text_IO;

procedure Evaluate_Expression is

   function Evaluate (E : Unbounded_String) return Unbounded_String is
   begin
      ...
   end Evaluate;

   Expression : Unbounded_String;

begin
   Put("Input: ");
   Get_Line(Expression);  -- This is Unbounded_IO.Get_Line.
   Put_Line(To_Unbounded_String("Output: ")
            & Expression
            & To_Unbounded_String(" = ")
            & Evaluate(Expression));
end Evaluate_Expression;
于 2015-03-01T00:30:37.947 回答
0

Ada 无法拥有动态字符串等

Ada 没有这样的能力,你只需要使用结构来提供你想要的动态能力。在这种情况下,您需要使用对象和指针(记录和访问)。您的对象封装输入数据并提供组合它们的功能。显然,您还有不同类型的输入数据、数字和运算符,因此您需要将其构建到您的对象中(使用继承)。

基本上你想使用 OOP 来存储和操作输入的数据。

于 2015-02-28T23:26:10.230 回答