Write to file using an implicit do loop

I need a help about implicit do loop in Fortran. This is my simple code:

Program Simple

Implicit none

Integer::i,j
Integer,parameter::N=2,M=3
Real,dimension(N,M)::Pot

Open(1,File='First.txt',Status='old')

    Read(1,'(M(f3.1,1x))') ((Pot(i,j),j=1,M),i=1,N)

Close(1)

Open(2,File='Second.txt',Status='Unknown')

    Write(2,'(M(i0,1x,i0,1x,f3.1,1x))') ((i,j,Pot(i,j),j=1,M),i=1,N)

Close(2)

Stop
End program Simple

This is the file First.txt:

1.1 1.2 1.3
2.1 2.2 2.3

When I try to execute this program I got a this message:

Unexpected element 'N' in format string
Unexpected element 'M' in format string

I want to keep the name of integer variables N and M in write statement. Is there any way to also keep their values from declaration part?

Answers


You are using M and N in the string (as characters), not as variables. In order to use the variables you need to write their values into the format string:

character(len=128) :: fmtString
!...
write(fmtString,*) M
fmtString = '('//trim(adjustl(fmtString))//'(f3.1,1x))'
Read(1,fmtString) ((Pot(i,j),j=1,M),i=1,N)

And similarly for the write statement.

However, you can probably use list-directed input (Read(1,*)) for the input, and let Fortran figure out the exact format.

Instead of this string manipulation you can use (*(f3.1,1x)) in modern compilers, or if you have an old one just specify a very large number, e.g. (99999(f3.1,1x)). In both cases, the correct number of values will be printed. However, this will result into writing all m*n values in one single line [thanks @agentp for pointing this out].


Need Your Help

Search with Ruby on Rails

html ruby-on-rails ruby search

I am currently learning Ruby on Rails, however, I have run into a slight issue, I am unable to create a text field from which to search. I so far have a working DB and web page (albeit an ugly one),

what happens when a sqlite3 db write is interupted?

python sqlite

Question: When does the actual writing to the sqlite3 db file take place and what happens if it is interrupted?