My code so far. It does not work however. I would like to be able to write something like "go", "car" or "truck", as long as it's 5 characters or less, and the programme will then write that word out. I think i need to use Get_Line an Put_Line but i do not know how to use them.
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
procedure Ada_O1_1 is
I : Integer;
S : String(1..5);
begin
Put("Write a string with a maximum of 5 characters: ");
Get(S, Last =>I);
Put("You wrote the string: ");
Put(S(1..I));
end Ada_O1_1;
CodePudding user response:
Get_Line returns a varying length String result and Ada requires that String objects have a known size at instantiation. The way around this is to initialize a String variable with the Get_Line result. You can do this inside a declare block:
declare
Line : String := Get_Line;
begin
-- Do stuff here like check the length of the Line variable and
-- adjust how your code works based on that. Note that the Line
-- variable goes out of scope once you leave the block (after "end")
end;
Inside the begin/end part of the block you can check the length of the line returned and verify that it is less than or equal to 5 and do your error handling based on that result.
CodePudding user response:
I put this in the form of a loop, which (a) makes using it slightly easier, (b) adds the need for handling empty and over-length inputs.
with Ada.Text_IO; use Ada.Text_IO;
procedure Ada_O1_1 is
I : Integer;
S : String (1 .. 5);
begin
loop
Put ("Write a string with a maximum of 5 characters (end with <RET>): ");
Get_Line (S, Last => I);
exit when I = 0; -- i.e. an empty line
if I = S'Last then
-- there are still characters in the input buffer
Skip_Line;
end if;
Put ("You wrote the string: ");
Put_Line (S (1 .. I));
end loop;
end Ada_O1_1;