Sagar Rawal
Sagar Rawal

Reputation: 399

How to break to new line in Fortran when printing?

It is very simple query but I'm not able to find the exact solution. How to break to new line when printing in Fortran?

for example

print*,'This is first line'
print*,'This is second line'

I want following output

This is first line

This is Second line

That is add space between two lines.

In java we use \n and in html using <br> does the job..but how to achieve same in Fortran?

Upvotes: 7

Views: 28420

Answers (2)

evets
evets

Reputation: 1026

There are several ways to print two lines of output.

program foo
   print *, 'This is the first line'
   print *, 'This is the second line'
end program

is one way to achieve what you want. Another is to do

program foo
   write(*,'(A,/,A)') 'This is the first line', 'This is the second line'
end program foo

And, yet another way

program foo
   write(*,'(A)') 'A' // achar(13) // achar(10) // 'B'
end program foo

And with some compilers you can use options

program foo
   write(*,'(A)') 'A\r\nB'
end program foo

Compiling with the following options yields:

$ gfortran -o z -fbackslash a.f90 && ./z
  A
  B

Upvotes: 10

francescalus
francescalus

Reputation: 32461

There are a number of ways to manage what you want. We can either print blank records or explicitly add a newline character.

A newline character is returned by the intrinsic function NEW_LINE:

print '(2A)', 'First line', NEW_LINE('a')
print '(A)', 'Second line'

NEW_LINE('a') is likely to have an effect like ACHAR(10) or CHAR(10,KIND('a')).

A blank record can be printed by having no output item:

print '(A)', 'First line'
print '(A)'
print '(A)', 'Second line'

Or we can use slash editing:

print '(A,/)', 'First line'
print '(A)', 'Second line'

If we aren't using multiple print statements we can even combine the writing using these same ideas. Such as:

print '(A,:/)', 'First line', 'Second line'
print '(*(A))', 'First line', NEW_LINE('a'), NEW_LINE('a'), 'Second line'

NEW_LINE('a') could also be used in the format string but this doesn't seem to add much value beyond slash editing.

Upvotes: 8

Related Questions