[英]How to add different type values to an array in Ada?
我的目標是從標准輸入中接收方程式,將其存儲在數組中以備后用/重新打印,然后輸出一行,打印整個方程式和答案,如下所示:
輸入: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很好,但是我不習慣強類型語法。 請詢問您是否需要更多信息。
Ada可以使用動態固定字符串,而無需求助於Unbounded_String或Containers或分配和指針,盡管這些是選項。
使之成為可能的見解是,在聲明字符串時,字符串可以從其初始化表達式中獲取其大小-但該聲明可以在循環內,以便每次在循環中重新執行一次。 您可能總不能構造一個程序使之有意義,盡管經常可能會有所思考。
另一個功能是,稍后,這些“聲明”塊將成為非常容易重構為過程的絕佳候選者。
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$
您仍然必須編寫計算器...
如果您要做的只是輸入一個可變長度的字符串,請將其提交給解析器並評估該字符串的求值器,然后將其與計算出的值一起反映出來,對於動態字符串處理,您可以簡單地使用Unbounded_Strings和Unbounded_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;
Ada無法擁有動態字符串等
Ada沒有這種能力,您只需要使用結構來提供所需的動態能力即可。 在這種情況下,您需要使用對象和指針(記錄和訪問)。 您的對象封裝了輸入數據並提供了將它們組合的功能。 顯然,您還具有不同類型的輸入數據,數字和運算符,因此需要將其構建到對象中(使用繼承)。
基本上,您想使用OOP來存儲和處理輸入的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.