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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

internal read/write, conversion str->real

Status
Not open for further replies.

mk95

Programmer
Nov 13, 2011
2
IT
Hi all!
I'm quite new in Fortran, and coming from other programming languages i was surprised in not finding here a function to convert a character variable in a numerical format ( and vice versa). I dug on the net for a solution and finally i found that you can use internal read/write for the purpuse. The problem is that i need to have this functionality in a function, but when i tried to create once i found out that i can't because of i'm not allowed to do I/O operation inside a function! There is no way to create a function with input a character, and output the corresponding number?

By
 
you are allowed to perform I/O inside a function (except if you have declared this one PURE). The only thing which is forbidden is to use such function in a WRITE statement.

And even this restriction has been removed in F2008, as far as I remember.

François Jacq
 
There are several ways of converting character strings to numbers: it depends on how much code you wish to write. The easy way is
Code:
integer function strtoint(str)
   character*(*), intent(in):: str
   integer result
   read(str,*) result
   strtoint = result
end function strtoint
As you have discovered, on the older version of Fortran, you can't do somethng like
Code:
str = '1234'
write (*,*) strtoint(str)
Although, having said that, would it not be easier to do something like
Code:
write (*,*) str
You can, of course, parse the string manually
Code:
integer function strtoint(str)
   character*(*), intent(in):: str
   integer result, posn, posnmax, zero
   posnmax = len(str)
   zero = ichar('0')
   do posn = 1, posnmax
      result = result * 10 + ichar(str(posn:posn)) - zero
   enddo
   strtoint = result
end function strtoint
A lot more work is required for negative numbers, floats, exponentials, double precision and complex numbers and error handling. It also assumes that the digits for 0..9 are sequential. The algorithm will have to change dramatically if they are not so maybe it is a lot to do the operation in two stages and use the read statement to extract the number.
 
I think the problem was that i was using the silverfrost plato compiler.. now with gfortran the problem is gone. I didn't thought about the "manual" solution at all, though, and is pretty simple/useful! Thanks a lot!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top