Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write a program where you can enter a maximum of 5 characters in a string, but also less than 5(in Ada)?

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;
like image 413
Louise Avatar asked Nov 20 '25 12:11

Louise


1 Answers

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.

like image 164
Jere Avatar answered Nov 23 '25 08:11

Jere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!