首页 > 解决方案 > Check if a character exists in an array in fortran

问题描述

So, I want to write some code so that the user cannot type in a city that is not in the city list, the city_list array is a one dimensional array of size 5 which values are A,B,C,D and E. So what I did was this

character, dimension(5) :: city_list 

do i=1,5
    city_list(i)= achar(i+64)         !To give the array a,b,c values to its first five components
end do

character :: City1, ...

do while(ANY(City_list == City1) )
    READ*, City1
    PRINT*, "IT'S GOT TO BE A,B,C,D,E"
end do

So I used the ANY function that I saw in another post, but I can' get to use it well, it doesn't seem to do what I asked it to do

标签: arraysfortranfortran90

解决方案


另一种方法可能是使用带条件的无限循环exit(使代码更简单......)

program main
    implicit none
    character :: city_list( 5 ), city1
    city_list = ["A", "B", "C", "D", "E"]

    do
        print*, "Introduce a city that is on the list"
        read *, city1
        if ( any( city1 == city_list ) ) exit
    enddo

    print *, "Your city1 is ", city1
end

推荐阅读