我正在编写我自1989年以来的第一个FORTRAN程序(使用FORTRAN77),这是我对现代FORTRAN的介绍。我在格式化write语句时遇到问题。具体地说,在读取实值和字符之后,我使用格式化的WRITE语句来允许用户检查输入。我可以使用一个未格式化的WRITE语句,一切都很好,但是如果我使用一个简单的格式化语句,结果输出就是垃圾。以下是我的MWE:
! MWE program testing formatted write of a real number
!
! bash cmd line gfortran-9 -o MWE_formated_write MWE_formated_write.f95
! build environment:
! Kubuntu 21.04 / kernel 5.11.0-34-generic
! GNU Fortran (Ubuntu 9.3.0-23ubuntu2) 9.3.0
! laptop w/ 4x Intel i5-5200U @ 2.2 GHz w/ 8 GiB ram
!
program MWE_formated_write
!
implicit none
real :: temp_input ! input temperature
character(len=1) :: temp_input_units ! input temperature unit, [F]/[C]/[R]/[K]
!
! Get input temperature and temperature units
!
write(*,*) "Enter the temperature and units F/C/R/K: "
read(*,*) temp_input, temp_input_units
!
! verify the input temperature and temperature units
!
write(*, *) " You entered (raw):", temp_input, temp_input_units
write(*, '(23A, 1X, F4.1, 2X, 1A)') "You entered (formated):", temp_input, temp_input_units
!
stop
end program MWE_formated_write以及对输出的捕获:
joseph@bohr:~/Projects$ gfortran-9 -o MWE_formated_write MWE_formated_write.f95
joseph@bohr:~/Projects$ ./MWE_formated_write
Enter the temperature and units F/C/R/K:
95 F
You entered (raw): 95.0000000 F
You entered (formated):�BF我预计第二行会输出"You entered (formated):95.1F“。
谢谢你的建议。
发布于 2021-09-13 07:02:17
您的代码中有一个简单的bug,其中的format字段显示为23A。这意味着在stdout上有23个字符对象要打印,而实际上只有1个。我想您所指的是宽度为23的单个字符对象。但对于长度为23的输出字符串来说,即使是23也可能太小。也许像30这样的数字会更合适。然后,还有实数宽度的问题,要求仅为4,这在大多数情况下太窄了。通常,最好指定比指定精度(此处为1)长7个字符或更多字符的宽度。下面的方法可以解决这两个问题。但更好的方法是使用现代的Fortran通用描述符g0,它可以自动处理所有类型的对象。g0编辑描述器的完整描述相当冗长,但它有效地消除了用户指定记录的宽度和类型的负担,并将其留给编译器。g0.d规范意味着如果编译器遇到real数字,那么它应该将输出记录的精度设置为小数点后的d位,否则对于字符或整数输出将忽略它。
格式中的' '强制编译器用一个空格分隔每个输出记录。将其更改为',',它将成为逗号分隔的值集(CSV)。
格式中的:有一个有趣的故事,它是Fortran2008标准中的一个拼写错误,但现在有了跳过添加最后一个分隔符的实用程序,在本例中,最后一个分隔符是一个空白" "。
program MWE_formated_write
use iso_fortran_env, only: RK => real64
implicit none
real(RK) :: temp_input ! input temperature
character(len=1) :: temp_input_units ! input temperature unit, [F]/[C]/[R]/[K]
! Get input temperature and temperature units
write(*,"(*(g0.10,:,' '))") "Enter the temperature and units F/C/R/K: "
read(*,*) temp_input, temp_input_units
write(*,*) temp_input, temp_input_units
! verify the input temperature and temperature units
write(*,"(*(g0,:,' '))") " You entered (raw):", temp_input, temp_input_units
write(*, '(A30, 1X, F10.1, 2X, 1A)') "You entered (formated):", temp_input, temp_input_units
end program MWE_formated_write以下是使用英特尔ifort的程序输出:
Enter the temperature and units F/C/R/K: 123 C
123.000000000000 C
You entered (raw): 123.0000000000000 C
You entered (formated): 123.0 Chttps://stackoverflow.com/questions/69139455
复制相似问题