Extract integers from a string in Fortran

I am using Fortran 90. I have a line 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 integers. Then I need to select the numbers from this line and assign them to the appropriate variables. Here is how I tried to do this:

  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 was not declared as an array or function. [FOLD]

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

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

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

syntax error around unexpected token `j '

How can I extract these numbers?

0
source share
2 answers

You can use the built-in index function to determine the location in the line of the first colon, for example, i . Then use internal reading to read the integer x from the previous substring: read (string (1:i-1), *) x . Then apply this procedure to the substring starting at i+1 to get y . Repeat for z .

PS. Your error messages from bash, not Fortran compiler?

+2
source

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

Without this, the compiler considers folds to be either an array (which is not the case) or a function (which is not what you want). It means that:

This name was not declared as an array or function.

But in terms of solving your problem, I will answer @MSB second because it is more elegant. Also, with the loop as it is (with the correction (j:j) both folds and temp_fold ), you rely on every x, y and z being integers. This other answer is much more general.

+1
source

Source: https://habr.com/ru/post/970426/


All Articles