Coding Ada: get vs. get_line (i) – the basics

Ada is a very strict language, but then it has to be, as it was designed for creating real-time systems. It does have some idiosyncrasies, but then all languages do. Let’s look at the two functions get() and get_line().

get()

The function get(), reads a value from the standard input. It knows what to read based on the argument it is given. For example the following piece of code allows an integer to be read into value x.

x : integer;
get(x);

Here are the characteristics of get():

  • For numbers it skips whitespaces (including newlines).
  • For characters and strings it reads exactly the right number of characters, but excludes newlines in count.

For example consider the following code:

s : string(1..4);
get(s);

Then the input from the user could be either one of:

tool
t
o
o
l

get_line()

The function get_line(), reads an entire line, i.e. a string. It stops reading when it encounters a line terminator (or rather if the end of the line is encountered, it automatically calls skip_line). Ada offers two ways to use get_line:

s : string(1..4);
len : natural;
s := get_line;
get_line(s,len);

The first (Line 3) treats get_line like a function, the other (Line 4) treats it like a procedure. Note there is a second parameter in the latter call, len. This returns the length of the string read in (the second parameter should be omitted for unbound_string). When using these two, there are different outcomes. Consider the following code, which reads in a fixed string.

s : string(1..4);
s := get_line;
put(s);

This code will only work when the string input is exactly 4 characters in length. Any other length will throw an exception. This is unlike C which allows more or less to be read. Alternatively, consider the following code:

s : string(1..4);
len : natural;
get_line(s,len);
put(s); put(len);

In this case, the value stored in s will be any string less than or equal to 4 characters in length, with the size stored in len. To circumvent these issues, often an unbound_string is used, which will basically read any size string up until the line terminator (typically a <return>). The code would look like this:

buf : unbounded_string;
buf := get_line;
put(buf);

Further reading:

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.