str2num and num2str functions in Fortran
Remember those handy functions from MATLAB str2num()
and num2str()
that convert strings to numbers and vice-versa? They come in handy from time to time.
Well, Fortran is quite capable of the same functionality, just not in that explicit way.
It's simple really: you may use write()
statement to write some data into a variable, or read()
statement to read it from one.
For example, if I'd like to convert my REAL :: num
into a string CHARACTER(LEN=15) :: str
, I'd go:
write(str , *) num
This piece will convert my num to string.
On the other hand, if I need to convert a string to number, I use read()
statement:
read(str , *) num
This will convert my string to number.
Format of a number will automatically be detected because of *
inside read() and write() statements.
In my experience, this works pretty well. If you find any problems, let me know.