Ada: subprogram that ignores initial blank spaces

308 views Asked by At

I'm interested in finding out if there is a way to create a "Get" subprogram for strings that works like "Get" for Integers or Float. As I understand the Ada get procedure for Integers ignores any type in of blank spaces before the integer and only collects the integer value.

Let's say we want to collect a string of five characters that should be stored in the variable "S" but the user type in 10 blank spaces and then the string so it would look something like this: Put in a string of 5 characters: buses I would like to create a "Get" that ignore these blank spaces and only gives my program the string value of 5 characters.

This is my main program.

S : String (1 .. 5);
begin
Put("Put in a string of 5 characters: ");
Get(S);
Put_Line(S);

I've read something about a function End_Of_Line. I understand that i need to create some kind of subprogram that collects the string and skips all initial blank spaces but I have not come up with a working solution.

Update: I tried to create my own get but got a little bit stuck. The get procedure should read the next character if the previous is ' ' but if it reads "the correct" string, how should the code look like?

       procedure Get(Item : in out String) is
      
      Ch : Character;
   begin
      
      loop
     Get(Ch);
     if Ch = ' ' and (not End_Of_Line) then
        Get(Ch);
     else 
       exit;
     end if;
      end loop;
      
   end Get;
1

There are 1 answers

1
Niklas Holsti On

If you cannot find a predefined Get operation to do what you want, try to decompose the problem into smaller steps and program those steps into your new Get procedure.

Here is a suggestion: such a Get procedure could read characters one at a time (using Get(C), where C is a Character), and have two parts:

  • First part: if the character is a space (C = ' '), read the next character, and repeat until a non-space character is read.

  • Second part: add the character just read to the string (the output parameter) and read the next character, repeating until the string contains five characters.

For both parts you have to consider what to do if the input line ends before the desired kind or number of characters have been read. You can detect that with the End_Of_Line function (which you call before reading each character). In case of end of line, should the procedure continue to the next input line? Or should it report an error, for example by raising an exception? Or should it return spaces in the output string, instead of the missing characters?