next up previous contents
Next: LOGICAL Data Up: CHARACTER data Previous: CHARACTER variables

I/O

When writing out character data using a FORMAT statement use the A field descriptor. The field width should match the number of characters held in the variable so for data held in real and integer variables of normal length use A4 For character variables use the declared size e.g. for a variable or array element that is declared CHARACTER*60 use A60. If the field width does not match the number of characters held in the variable or array element then, just like assignments, the right hand end is truncated or extended with spaces.

Exercise 14

Type in the following program that allows a user to create an address and telephone directory in the file ADDRES.DAT. The directory is called KDIR, the first 15 characters hold the name, the next 50 the address and the last 15 the telephone number.

        CHARACTER*80  KDIR(100)
        CHARACTER*15  KNAME,KTELNO
        CHARACTER*50  KADDR
 
 
c      Set up maximum and current number of addresses
        MXDIR=100
        NDIR=0
 
 
c       Ask user for next entry.
100     PRINT *,'NAME:'
        READ 90000,KNAME
90000   FORMAT(A15)
        PRINT *,'Address:'
        READ 900001,KADDR
90001   FORMAT(A50)
        PRINT *,'Telephone number:'
        READ 90000,KTELNO
 
        NDIR=NDIR+1
        KDIR(NDIR)=KNAME//KADDR//KTELNO
        IF (NDIR.GE.MXDIR) THEN
          PRINT *,'Directory is now full'
          GOTO 300
        ENDIF
 
 
c       See if user wants to add another entry
200     PRINT *,'Do you want to add another entry-type Y or N'
c       (here is an example using a real to hold 1 character with
c       padding spaces)
        READ 90002,ANS
90002   FORMAT (A1)
        IF (ANS.EQ.'Y') THEN
          GOTO 100
        ELSE IF(ANS.EQ.'N') THEN
          GOTO 300
        ENDIF
        GOTO 200
 
 
c       Output directory file
300     LUNDIR=20
        OPEN(UNIT=LUNDIR,FILE='ADDRES.DAT',STATUS='NEW')
        WRITE(LUNDIR,90003) NDIR
90003   FORMAT(' Directory contains',I5,' entries',//)
        WRITE(LUNDIR,90004) (KDIR(I),I=1,NDIR)
90004   FORMAT(' ',A80)
        CLOSE(UNIT=LUNDIR)
        PRINT *,'Directory file ADDRES.DAT created'
        STOP
        END
When the program is working (check it by listing out ADDRES.DAT) write a second program to read the file back in, ask the user for a name and then search the directory for the address and telephone number. (A clever program might accept just the first few characters of a name and list out all entries that match it).
* * *


next up previous contents
Next: LOGICAL Data Up: CHARACTER data Previous: CHARACTER variables
n west (APC)
2000-03-08