[英]Read an allocatable string with a namelist in Fortran
由於Fortran 2003可以使用可變長度的字符串。 我不想以古老的方式工作並聲明一個恆定的字符串長度,而是想動態地讀取我的名單中的字符串。
考慮一下該計划
program bug
implicit none
character(:), allocatable :: string
integer :: file_unit
namelist / list / string
open(newunit=file_unit,file='namelist.txt')
read(unit=file_unit,nml=list)
write(*,*) string
close(file_unit)
end program bug_namelist
以及namelist.txt文件中包含的小名單:
&list
string = "abcdefghijkl"
/
如果我用GCC 8.2.0編譯帶有激進的調試標志,我得到
Warning: ‘.string’ may be used uninitialized in this function [-Wmaybe-uninitialized]
在runtine,什么都沒有打印出來,這就出現了:
Fortran runtime warning: Namelist object 'string' truncated on read.
使用具有類似調試標志的英特爾編譯器17.0.6,沒有編譯時標志和以下運行時錯誤:
forrtl: severe (408): fort: (7): Attempt to use pointer STRING when it is not associated with a target
這表明namelist功能無法“自行”分配可變長度字符串,因為如果我添加該行
allocate(character(len=15) :: string)
錯誤消失了。 這是預期的行為嗎? 或者它是編譯器的缺陷?
這是Fortran標准規定的預期行為。 實際上,Fortran I / O中沒有任何地方延遲長度可分配字符串處理它們在內部賦值中的方式。 有一個建議的工作項目用於下一個Fortran標准(“F202X”),以便在有限的環境中實現這一點(參見https://j3-fortran.org/doc/year/18/18-279r1.txt )如果我記得正確地說,我們討論過在早期的標准會議上添加列表導向和NAMELIST讀取,但提出了一些我不記得的問題,我們將重新審視這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.