问题
I am trying to convert an integer to character in my program in Fortran 90. Here is my code:
Write(Array(i,j),'(I5)') Myarray(i,j)
Array
is an integer array and Myarray
is a character array, and '(I5)'
, I don't know what it is, just worked for me before!
Error is:
"Unit has neither been opened not preconnected"
and sometimes
"Format/data mismatch"!
回答1:
Alexander Vogt explains the meaning of the (I5)
part. That answer also points out some other issues and fixes the main problem. It doesn't quite explicitly state the solution, so I'll write that here.
You have two errors, but both have the same cause. I'll re-state your write statement explicitly stating something which is implicit.
Write(unit=Array(i,j),'(I5)') Myarray(i,j)
That implicit thing is unit=
. You are, then, asking to write the character variable Myarray(i,j)
to the file connected to unit given by the integer variable Array(i,j)
.
For some values of the unit integer the file is not pre-connected. You may want to read about that. When it isn't you get the first error:
Unit has neither been opened not preconnected
For some values of Array(i,j)
, say 5, 6 or some other value depending on the compiler, the unit would be pre-connected. Then that first error doesn't come about and you get to
Format/data mismatch
because you are trying to write out a character variable with an integer edit descriptor.
This answer, then, is a long way of saying that you want to do
Write(Myarray(i,j),'(I5)') array(i,j)
You want to write the integer value to a character variable.
Finally, note that if you made the same mistake with a real variable array
instead of integer, you would have got a different error message. In one way you just got unlucky that your syntax was correct but the intention was wrong.
回答2:
'(I5)'
is the format specifier for the write statement: write the value as an integer
with five characters in total.
Several thing could go wrong:
- Make sure that
Myarray
really is an integer (and not e.g. areal
) - Make sure
array
is a character array with a length of at least five characters for each element - Take care of the array shapes
- Ensure that
i
andj
hold valid values
Here is a working example:
program test
implicit none
character(len=5) :: array(2,2)
integer,parameter :: myArray(2,2) = reshape([1, 2, 3, 4], [2, 2])
integer :: i, j
do j=1,size(myArray,2)
do i=1,size(myArray,1)
write(array(i,j), '(I5)' ) myArray(i,j)
enddo !i
enddo !j
print *, myArray(1,:)
print *, myArray(2,:)
print *,'--'
print *, array(1,:)
print *, array(2,:)
end program
来源:https://stackoverflow.com/questions/30643905/converting-integer-to-character-in-fortran90