Anton B
Anton B

Reputation: 181

Extract integers from string in Fortran

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?

Upvotes: 0

Views: 2526

Answers (2)

francescalus
francescalus

Reputation: 32366

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.

Upvotes: 1

M. S. B.
M. S. B.

Reputation: 29391

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?

Upvotes: 2

Related Questions