0

I searched it on the forum but couldn't find an answer to my question. If I missed something, I am sorry. So, here is my question:

I have a code as below:

program averagepro
implicit none
real,allocatable,dimension(:) :: a
real :: realfunctionaverage
integer :: i,n
character :: response,filename
print*,'How many numbers would you like to enter?'
read*,n
allocate(a(n))
print*,'Would you like to enter numbers by reading from a file or from the keyboard?'
print*,'Press "F" to enter using a file or "K" to enter from keyboard.'
read*,response
if  (response=='F' .or. response=='f') then
    print*,'Please enter the name correctly, as well as regarding capital letters and file extension: '
    read*,filename
!   print*, filename
!   open(12,file='array.txt')
    open(12,file='filename')
    do  i=1,n
        read(12,*) a(i)
    enddo
elseif  (response=='K'.or. response=='k') then
    print*,'Please enter the numbers, one at each time: '
    do  i=1,n
        read*,a(i)
    enddo
else
    stop
endif
write(*,10) ' The average of the numbers entered are: ',realfunctionaverage(n,a)
10  format(a,2f10.3)
deallocate(a)
end program averagepro 
!--------------------------------------------------------------------------------------------------------
function realfunctionaverage(m,list)
implicit none
integer :: m,i
real,dimension(m) :: list
real :: realfunctionaverage,ans
ans=0
do  i=1,m
    ans=ans+list(i)
enddo
realfunctionaverage=ans/m
end function realfunctionaverage

I am having problem while I try to enter the file name from the keyboard. When the program asks for the file name, I define it as "array.txt" or "array"; but it gives an error and stops running. How should I do it? By the way, when I disable somelines and directly write the filename which is "array.txt", program works properly.

1
  • 1
    Maybe it's worth to specify what error does exactly occur?
    – Fedor
    Jan 9, 2015 at 0:00

1 Answer 1

2

You are attempting to open the file called "filename" no matter what the user enters. This line:

open(12,file='filename')

should be:

open(12,file=filename)

With quotes it is the string literal "filename", without quotes it is the contents of the variable named filename.

You will also need to declare the variable filename with some length to accommodate a filename.

character(len=256) :: filename

should be adequate for most use cases. Without a len, the character variable can only hold a single character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.