Ada Programming/Libraries/Ada.Text IO
The package Text_IO
Used for simple Input Output (IO) in text format.
Tips and Tricks for Text_IO
Read a whole line from the console
Ada 2005 has a function
Get_Line which returns a newly created string containing the whole line:
With older Ada generations, you need a little work to get the complete line with one call.
Get_Line procedure gets a line of text of as many characters the Item can hold
or up to the new_line indicator, whichever comes first. (The new_line indicator's representation is
It has the following specification:
To be specific, consider an Item that can hold as much as 80 characters. Let's take two lines to read, one holding less that 80 characters, say 10, the other at least 80, perhaps more. Calling
Get_Line (Item, Last);
will read the first line up to the new_line indicator and consume them; Item's first 10 characters will be filled with the text read, the rest is junk; Last will hold the last filled index.
The next call will read the maximum Item can hold, i.e. 80 characters; the rest of the line (if any) and the
new_line indicator remain unconsumed.
Thus Last will be
Item'First - 1 + 80.
In order to consume the rest of the line, you have to call
The result will be like one of the two possibilities above, depending on the remaining line length.
If no characters are read (i.e. when the new_line indicator is the only thing left unread), Last will hold
Item'First - 1.
The following example shows how the complete line could be read:
renamesAda.Text_IO; Everything: Ustr.Unbounded_String := Ustr.Null_Unbounded_String; Item : String (1 .. 80); Last : Natural;
loopT_IO.Get_Line (Item, Last); -- * Ustr.Append (Source => Everything, New_Item => Item (1 .. Last)); -- *
whenLast < Item'Last; -- **
As an exercise, change the calls at (*) to
T_IO.Get_Line (Item (11 .. 20), Last); Ustr.Append (Source => Everything, New_Item => Item (11 .. Last));
and see which values Item and Last will hold. Which criterium will you then need to exit the loop at (**)?
(This is of course not a very sensible idea to code like this, but as a learning instruction, it's fine.)
Read a whole line from a file
In principle it is the same as in console reading but you have to check for the end of file as well:
End_of_File is always False for console input (except when you manage to enter the implementation defined end_of_file indicator).
A well-formed text file (i.e. one created with Ada.Text_IO) will always hold an end_of_line (and an end_of_page) indicator before the
end_of_file indicator (see procedure
- Ada Programming
- Ada Programming/Input Output
- Ada Programming/Libraries
- Ada Programming/Libraries/Ada
- Ada Programming/Libraries/Ada.Strings.Unbounded.Text IO
- Search Rosetta Code for examples using Ada.Text IO
- Search Stack Overflow for questions regarding Ada.Text IO
- Search GitHub for examples using Ada.Text IO
- Search for any Ada related page about Ada.Text IO