fortran internal read - convert character to integer

159 Views Asked by At

I have browsed through many articles (i.e. character to integer conversion in fortran) which suggest a solution to the problem. I just can't get it working although I think I follow the suggestions given. The main problem would be to have a text which I would like to store as an integer (don't ask why, the code is 35 year old which I would like to get up and running again). The minimum working example looks like:

program test
  integer :: LTS
  CHARACTER (len=1)  :: UBF
  UBF = "U"
  read(UBF,'(i1)')  LTS
  stop
  END

I compile with 'gfortran' (no matter whether v.4.8.5. or v.11) and the error is: 'At line 5 of file minimal.f Fortran runtime error: Bad value during integer read'

Printing out the variable UBF, I can see the string 'U'. It's there. I expected to get an integer value for 'U' in LTS.

I guess, I don't see the forest for the trees. Any help would be greatly appreciated. The OS is Redhat 7.9 if that had any influence.

Thanks, Chris

1

There are 1 best solutions below

1
Vladimir F Героям слава On

You can transfer bit patterns between variables of different type using the standard transfer function. The first argument is what you are converting and the other argument has the type to which you are converting.

For example,

number = transfer("u",number)
string = transfer(number, string)