Variable-Length String Input in Ada
Variable-Length String Input in Ada
Jeffrey R . Carter
Senior Engineer, Softwar e
Martin Marietta Astronautics Grou p
P. O . Box 17 9
Denver, CO 8020 1
On a number of occasions I have found myself discussing how long a string needs to be declare d
for input, usually user input . Is twenty characters enough? Is eighty too many? Doesn't 25 6
use too much memory? This question comes up even when dealing with some form of variabl e
string . The answer I always give is that the software should accept as many characters as th e
user enters, but have had to admit that declaring a string with POSITIVE'LAST characters is a
little excessive . I felt that there must be some way to use Ada to create a string of just the righ t
length, and have now figured out how to do that .
The basic concept is a recursive function which eventually returns a string of the lengt h
entered and skips the line terminator which marks the end of the string . This function resul t
can be used to initialize a constant string or be passed as the actual parameter to a subprogram
which has a string formal parameter of mode in . This function, which I call get_line, is :
with text_io ;
function get_line (file : text_io .file_type := text_io .current_input )
return string i s
char : character ;
begin °-• get_line
if text_io .end_of_line (file) the n
-° skip line terminator--ready to "get" next "line "
text_Lo .skip_line (file) ;
return "" ; — null string terminates recursio n
else
text Lo .get (file, char) ;
return char & get_line (file => file) ;
end if ;
end get_line ;
The default parameter value allows the function to be used without supplying an actua l
parameter . When this is done, the function reads from the default input file, which is the sam e
file read by the text_10 input subprograms which do not have file parameters .
The function can be used as described above ; for example, a simple command-line interprete r
might look like :
Apparently no one has described this approach to variable-length string input before . Muc h
work has been done on variable-string abstract data types in Ada . This simple function migh t
serve as an argument against the need for such a type, especially if it is being used only t o
facilitate input .
I would like to thank Geoff Mendal, technical editor of Ada Letters, for his valuable comments
on earlier versions of this article .