How to remove leading space when printing with write?
Asked Answered
W

2

13

Suppose I have the following code

program fortran
  open(900, FILE='SOMETHING')   
  write(900, *) '21'    
end program fortran

The file form will be

 21

that is, there is a space before the number. How to get rid of that space?

Windowsill answered 30/7, 2014 at 18:58 Comment(2)
In general, if you want control over formatting, you have to use formatted output, rather than unformatted/default formatting (eg, *).Ordain
Questions about list-directed IO not having the desired output are common. As already answered, use formatted IO instead.Are
U
13

You can write it as a string:

PROGRAM fortran 

  OPEN(900,FILE='SOMETHING')
  WRITE(900,'(a)') '21'

END PROGRAM FORTRAN
> cat SOMETHING 
21

To respond to the comment:

The more explicit way of doing that would be to write the number into a string (you could also use list-directed I/O for this step), remove whitespaces from the string trim and finally output the left-adjusted adjustl:

program test
  character(len=23) :: str

  write(str,'(ES23.15 E3)') 1.23d0
  write(*,'(a)') adjustl(trim(str))

  write(str,'(ES14.7 E2)') 0.12e0
  write(*,'(a)') adjustl(trim(str))
end program
> ./a.out 
1.230000000000000E+000 
1.2000000E-01

This solution is probably more complicated then necessary, but it is a very flexible approach that can be extended easily for arbitrary purposes and formats.

Uball answered 30/7, 2014 at 19:45 Comment(2)
I want to remove the leading space in real values also.Windowsill
us a zero field width, eg. write(*,'(f0.4)')3.14Luganda
H
4

In list-directed format (the * in write(unit,*)) the compiler typically inserts a leading space. The first column used to be used to control line printers but that is now deleted from Fortran.

You can use any explicit format you want to get rid of the leading space. For example the general g0 one or the string specific a or the integer-specific i.

Haircut answered 23/5, 2018 at 10:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.