Extract integers from string in Fortran

时光怂恿深爱的人放手 提交于 2020-01-16 19:40:54

问题


I'm using Fortran 90. I have a string declared as CHARACTER(20) :: Folds, which is assigned its value from a command line argument that looks like x:y:z where x, y, and z are all integers. I then need to pick out the numbers out of that string and to assign them to appropriate variables. This is how I tried doing it:

 i=1
 do j=1, LEN_TRIM(folds)
    temp_fold=''
    if (folds(j).neqv.':') then
        temp_fold(j)=folds(j)
    elseif (i.eq.1) then
        read(temp_fold,*) FoldX    
        i=i+1
    elseif (i.eq.2) then
        read(temp_fold,*) FoldY 
        i=i+1
    else
        read(temp_fold,*) FoldZ 
    endif
 enddo

When I compile this I get errors:

unfolder.f90(222): error #6410: This name has not been declared as an array or a function. [FOLDS]

[stud2@feynman vec2ascii]$ if (folds(j).neqv.':') then syntax error near unexpected token `j' [stud2@feynman vec2ascii]$ --------^

unfolder.f90(223): error #6410: This name has not been declared as an array or a function. [TEMP_FOLD]

[stud2@feynman vec2ascii]$ temp_fold(j)=folds(j)

syntax error near unexpected token `j'

How can I extract those numbers?


回答1:


You can use the index intrinsic function to locate the position in the string of the first colon, say i. Then use an internal read to read the integer xfrom the preceding sub-string: read (string (1:i-1), *) x. Then apply this procedure to the sub-string starting at i+1 to obtain y. Repeat for z.

P.S. Are your error messages from bash rather than a Fortran compiler?




回答2:


With folds a character variable, to access a substring one needs a (.:.). That is, to access the single character with index j: folds(j:j).

Without this, the compiler thinks that folds must be either an array (which it isn't) or a function (which isn't what you want). This is what is meant by:

This name has not been declared as an array or a function.

But in terms of then solving your problem, I second the answer given by @M.S.B. as it is more elegant. Further, with the loop as it is (with the (j:j) correction in both folds and temp_fold) you're relying on each x, y, and z being single digit integers. This other answer is much more general.



来源:https://stackoverflow.com/questions/21370190/extract-integers-from-string-in-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!