Chuyển đến nội dung

Bài 5 · Getting Started

Text_IO: Reading and Writing Text in Ada

Learn Ada.Text_IO and the generic packages for integers and floats: Put, Put_Line, Get, Get_Line, formatting with Width, 'Image, files and the standard streams.

Input and output in Ada live in the standard library, not in the language. The main package is Ada.Text_IO for characters and strings, with child packages Ada.Integer_Text_IO and Ada.Float_Text_IO for numbers. This lesson covers the calls you will use daily, how to format numbers, and how to read and write files.

As elsewhere, Ada code is shown read-only, with runnable C stand-ins that mimic the behavior.

Printing text

ADA
with Ada.Text_IO; use Ada.Text_IO;

procedure Print_Demo is
begin
   Put ("No newline, ");
   Put_Line ("then a line");
   New_Line;
   Put ('A');            --  a Character
   New_Line (2);         --  two blank lines
end Print_Demo;

Put writes without a line break; Put_Line adds one; New_Line writes a line terminator (with an optional count). There is no format string: you combine pieces yourself.

Printing numbers

Put for Integer does not live in Ada.Text_IO itself. You need a numeric package:

ADA
with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;
with Ada.Float_Text_IO;   use Ada.Float_Text_IO;

procedure Numbers is
   N : Integer := 42;
   F : Float   := 3.14159;
begin
   Put (N, Width => 6);          --  "    42"
   New_Line;
   Put (F, Fore => 2, Aft => 3, Exp => 0);   --  " 3.142"
   New_Line;
end Numbers;

The parameters control layout: Width is the minimum field width for integers; Fore the digits before the point, Aft after it, and Exp the exponent digits (0 means no exponent).

The quickest way to turn a value into text is the attribute 'Image:

ADA
Put_Line ("Count = " & Integer'Image (N));     --  "Count =  42"
Put_Line ("F = " & Float'Image (F));

Note that Integer'Image (42) gives " 42" with a leading space for the sign. Trim it with Ada.Strings.Fixed.Trim, or use N'Image in Ada 2012 and later.

Reading input

ADA
with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Echo is
   Age  : Integer;
   Line : String (1 .. 80);
   Last : Natural;
begin
   Put ("Age? ");
   Get (Age);
   Skip_Line;                      --  discard the rest of the line

   Put ("Name? ");
   Get_Line (Line, Last);          --  Last = number of characters read
   Put_Line (Line (1 .. Last) & " is" & Integer'Image (Age));
end Echo;

Get (Age) reads an integer token and leaves the line terminator behind, so call Skip_Line before a Get_Line. Get_Line (Buffer, Last) fills the buffer and tells you how many characters it stored. If the user types text where a number is expected, Get raises Data_Error; at the end of input it raises End_Error. You will handle those in the exceptions chapter.

Files

Text_IO works with File_Type objects:

ADA
declare
   F : File_Type;
begin
   Create (F, Out_File, "notes.txt");
   Put_Line (F, "first line");
   Close (F);

   Open (F, In_File, "notes.txt");
   while not End_Of_File (F) loop
      Put_Line (Get_Line (F));
   end loop;
   Close (F);
end;

Without the File parameter, Put and Get use the standard streams (Standard_Input, Standard_Output, Current_Error). Put_Line (Standard_Error, "oops") writes to the error stream.

Stand-in: formatted output and line reading in C

printf field widths work like the Width, Fore and Aft parameters. This labelled C stand-in prints the same layouts as the Numbers procedure above.

C Stand-in: field width and decimals

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Reading is the other half. This stand-in shows the "token, then discard the rest of the line, then read a line" pattern, using preset program input. Put some text into the Program input box, for example 37 on the first line and Grace Hopper on the second.

C Stand-in: Get, Skip_Line and Get_Line

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

If you delete the Skip_Line loop, fgets reads the empty remainder of the first line, which is the classic beginner bug in Ada too.

Choosing between the styles

  • Quick messages: Put_Line ("Total: " & Integer'Image (Total));.
  • Aligned columns: Put (Item, Width => 8).
  • Money or measurements: Ada.Float_Text_IO.Put with Aft set.
  • Rich formatting, JSON or tables: use a library such as GNATCOLL, or build the strings yourself.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why does Put (42) need an extra with clause?

    The numeric Put procedures are in separate instantiated packages such as Ada.Integer_Text_IO and Ada.Float_Text_IO.
  2. 2. What does Skip_Line do after Get (Age)?

    Get leaves the line terminator unread, so a following Get_Line would return an empty line unless you skip it.
  3. 3. What does Integer'Image (7) return?

    For non-negative values 'Image gives a leading blank where a minus sign would go.
  4. 4. Which exception does Get (N) raise when the input is not a number?

    Text_IO raises Data_Error when the characters do not form a valid value of the requested type.

Summary

  • Put, Put_Line, New_Line, Get, Get_Line and Skip_Line are the core of Ada.Text_IO.
  • Integers and floats are printed through Ada.Integer_Text_IO and Ada.Float_Text_IO, with Width, Fore, Aft and Exp.
  • 'Image converts a scalar to a string (with a leading space for non-negative numbers).
  • Files use File_Type, Create, Open, Close and End_Of_File.

Next: Integer and Floating-Point Types

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.