Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Trouble with comparing character strings in Fortran

Status
Not open for further replies.
Jul 17, 2014
4
US
Hello all

So I am working on some basic Fortran (FORTRAN) programs in order to learn the basics. I have some experience coding in C++ before this

Im trying to write some basic input control structures, ie

Code:
      PROGRAM MENU
      implicit none
      character (LEN=5):: input
      write(*,*)'==Age Database=='
      do while(input/='Q'.or.input/='q')
        write(*,*)'==Main Menu=='
        write(*,*)'> '      
        read(*,*)input
        if(input=='P'.or.input=='p')
          write(*,*)'P command activated'
        end if
      end do
      stop
      end program MENU

But when I go to compile it with gfortran (ahh, gfortran -o menu menu.f)

I get

gfortran said:
menu.f:9.72:

if(input=='P'.or.input=='p')
1
Error: Cannot assign to a named constant at (1)
menu.f:11.11:

end if
1
Error: Expecting END DO statement at (1)

Which I dont understand, since I thought == was a comparison operator, not the assignment one. Is it absolutely necessary to declare another character string , assign 'P' or 'p' to it, and check it in that case?
 
You are missing the then

Also, since input has been declared as character(len=5), trim it before comparing. Unlike C, there is no string terminator. Fortran strings are space padded so it will be comparing 'P ' against 'P'.
 
So is the then keyword required for all if statements, or just ones that compare strings?

How exacty do I "trim" the input variable?
 
Not always, depends on how you write the if statement.
Code:
! Then not required
if (condition) dosomething
! Then  required
if (condition) then
    dosomething
end if
Trimming
Code:
if(trim(input)=='P'.or.trim(input)=='p') then
    ...
 
not equal" is working for me, I had to change the "do while" around:
Code:
PROGRAM MENU
      implicit none
      character (LEN=5):: input
      write(*,*)'==Age Database=='
      do ! while(input/='Q'.or.input/='q')
      
        write(*,*)'==Main Menu=='
        write(*,*)'> '      
        read(*,*)input
        if ( input=='P' .or. input=='p') then
          write(*,*)'P command activated'
        end if
        
        if ( input=='Q' .or. input=='q') exit
      end do
      stop
end program MENU
No need for trim, by the way, in this case; but do learn about it.
 
Sorry...I meant to say that "not equal" it's not working for me
 
It is a logic error. Should be
Code:
    do while (input /= 'Q' .and. input /= 'q')
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top