How to return a string without trailing spaces

How to return a string without trailing spaces

Dear all,

I would like to write a function that will return a string, but I do not want the string contains trailing spaces. How could I do it? Thanks!

Do few things, and do them well!
9 Beiträge / 0 neu
Letzter Beitrag
Nähere Informationen zur Compiler-Optimierung finden Sie in unserem Optimierungshinweis.
Bild des Benutzers Repeat Offender

You could write a specification function that computes the length of the function result. Sometimes this isn't feasible, though, for example when the function returns the next line of input. In this case the function result may be declared as allocatable length. In either case the interface must be explicit in the calling program unit.

Bild des Benutzers Steve Lionel (Intel)

You can also do it with a function that returns a deferred-length allocatable character result.

Steve

Zitat:

You can also do it with a function that returns a deferred-length allocatable character result.

Can you give me an example solution of this:

character(1000) function foo()

foo = "abc"

end function foo

where I would like foo() to return "abc", not "abc" with huge number of spaces.

Do few things, and do them well!
Bild des Benutzers Steve Lionel (Intel)
Best Reply

function foo()
character(:), allocatable :: foo
foo = "abc"
end function foo

You must have an explicit interface for this visible to the caller - the easiest way to do that is to put the function in a module and then USE the module in the program units where you want to call the function.

Please note also that you need a reasonably current compiler (12.1 minimum, I think), for this to work.

Steve

Thank you, Steve!

Do few things, and do them well!

I am still having a problem as:

function foo()

character(:), allocatable :: foo
character(1000) bar

bar = "abc"
foo = trim(bar)

end function foo

The content of foo still includes trailing spaces.

Do few things, and do them well!
Bild des Benutzers Steve Lionel (Intel)

I tried it and it worked correctly for me. Here's the test program I used and its output:

print '(A,A,A)', '*',foo(),'*'
contains
function foo()

character(:), allocatable :: foo
character(10) bar

bar = "abc"
foo = trim(bar)

end function foo
end

*abc*

Steve

Thanks, again! "ifort" can behave properly, but "gfortran" still add the trailing spaces!

Do few things, and do them well!

Melden Sie sich an, um einen Kommentar zu hinterlassen.