用写打印时如何去除前导空间? [英] How to remove leading space when printing with write?

查看:63
本文介绍了用写打印时如何去除前导空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下代码

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

文件格式为

 21

,即数字前有一个空格.如何摆脱这个空间?

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

推荐答案

您可以将其写为字符串:

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:

更明确的方法是将数字写入字符串(您也可以在此步骤中使用列表控制的I/O),从字符串

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.

这篇关于用写打印时如何去除前导空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆