Previous | Next | Table of Contents | Index | Program List | Copyright

9.5 Problem Solving: Getting Input Values from a String

Ada.Text_IO provides Get and Put operations that do not use files at all. Each of the Get operations takes its input from a string instead of either Standard_Input or a named file. For example, suppose we have

    Line           : String(1..80);
    LineLength     : Natural;
    
    IntegerVariable: Integer;
    IntLast        : Natural;
    
    FloatVariable  : Float;
    FloatLast      : Natural;
We can read an entire line (of 80 characters or less) into Line and then read individual values from that string. Suppose we know that the first value in the line is supposed to be an integer value and that the second value is supposed to be a float value. We can write
    Ada.Text_IO.Get_Line (Item => Line, Last => LineLength);
and then read from the string Line into the integer variable
    Ada.Integer_Text_IO.Get
      (From => Line, Item => IntegerVariable, Last => IntLast);
which reads the first token from Line, converts it to integer form, and stores it in IntegerVariable. The behavior of this Get is identical to the other integer Gets--for example, raising Ada.Text_IO.Data_Error if the first token is not a string representing an integer value--except that input comes from a string instead of a file. The variable IntLast contains the index (in Line) of the last character read.

Now we can read the second token as a float value, by writing

    Ada.Float_Text_IO.Get
      (From => Line(IntLast+1..Line'Last), 
       Item => FloatVariable,
       Last => FloatLast);
    
Note that as with the From parameter, we must specify the slice of Line that follows the first (integer) value.

This input style is used in writing "industrial-strength" robust input procedures. For example, such a procedure could handle a Data_Error exception by rereading the token using a different Get.

To reiterate: all the Gets--character, string, integer, float, and enumeration--have three forms:

Exercises for Section 9.5

Self-Check

  1. Suppose that the name of a text file given as a parameter to Ada.Text_IO.Open is not a valid file name or that the file cannot be found in the current directory. What happens? When does it happen?

Programming

  1. "Hard-wiring" the name of a file into a program is usually considered to be poor programming style, because it limits the flexibility of the program. Rewrite Copy_File ( Program 9.3) so that the names of the input and output files are read as strings from the keyboard. (Hint: Use Get_Line.)


Previous | Next | Table of Contents | Index | Program List | Copyright

Copyright © 1996 by Addison-Wesley Publishing Company, Inc.