Iterating over a FORTRAN character array
Ok, I'm having mucho trouble with the following Fortran 90 code. The program tester should create a character array called input, initialize all the entries to the space character, then get some string from the user and store it in input. The getLength function is supposed to return the last index in the function that isn't a space; so if the user entered the string "Hello, how're you?", then getLength(input) should return 11. It's supposed to work by starting at the end of the given array, and marking where the first non-space character occurs. When I actually try to run it, gfortran says: "Error: Return type mismatch of function getLength at (1) (REAL(4)/INTEGER(4)). What does that mean, what am I doing doing wrong, and how should I fix it? Thanks in advance!
program tester
implicit none
character(len = 1000) :: input
external getLength
do i = 1, 1000
input(i) =开发者_运维问答 " "
end do
read *, input
print *, getLength(input)
end program
integer function getLength(array) result (length)
character(len=1000) :: array
integer :: lenTemp = 1000
do while (array(lenTemp:lenTemp) == ' ')
lenTemp = lenTemp - 1
end do
length = lenTemp
end function
it doesn't look like you're declaring the type of your external function getLength
so the compiler is assuming that getLength
is of the default type REAL(4)
. Consider swapping external getLength
for something with a type like INTEGER, EXTERNAL :: getLength
.
Also, it probably wouldn't hurt to include an IMPLICIT NONE
inside the function definition for extra clarity.
EDIT: Additionally, with the way Fortran handles character strings, you should simply initialize the variable input to either an empty string or one blank space. Fortran will always fill the remainder of a string with blanks when you don't fill it completely. You really should do something like CHARACTER(LEN=1000) :: input = ''
to properly initialize input
.
精彩评论