创建一个用于消息记录的重载函数 [英] Creating an overloaded function to be used in message logging
问题描述
我试图创建一个重载函数 num2str(x)
,它将整数或实数值作为输入并返回一个字符串值。我的目的是在编写日志文件时使用它。
I am trying to create an overloaded function num2str(x)
which will take integer or real values as input and return a string value. My purpose of doing this is to use it when writing log file.
根据我以前的文章( message(msglevel,string) / code>我正在用它来写我的日志文件。现在我只能发送一个字符串到这个函数,我试图很容易地使用 num2str(x)
创建一个字符串。
Based on suggestions given in my previous post (creating log file)
I have created a subroutine message(msglevel, string)
which I am using to write my log file. Now I can only send a string to this function and I am trying to make it easy to create a string using num2str(x)
.
有人可以解释我应该在哪里放置这段代码(在子例程中,在模块中),以便我可以从任何地方访问它。我看到了这个示例,但它使用它主程序,我不能这样做。
Could someone explain me where should I place this code (In a subroutine, in a module) so I can access it from everywhere. I saw an example of this, but it uses it in the main program, which I can't do.
请让我知道这种方法是否正确。我还想知道如果我可以修改 num2str(x)
返回数组变量的字符串。
Please let me know if this approach is correct.I would also like to know if I can modify num2str(x)
to return string for array variables.
!GLOBAL FUNCTIONS
interface num2str
function num2str_int(number)
integer,intent(in)::number
character(len=*)::num2str_int
end function
character function num2str_real(number)
real::number
character(len=*)::num2str_real
end function
end interface
function num2str_int(number)
implicit none
integer,intent(in)::number
character(len=*)::num2str_int
write(num2str_int,'(I)')number
return
end function
character function num2str_real(number)
implicit none
real,intent(in)::number
character(len=*)::num2str_real
write(num2str_real,'(F6.4)')number
return
end function
推荐答案
模块:
I would definitely go for a module:
module strings
! GLOBAL FUNCTIONS
public :: num2str
! Everything else is private
private
interface num2str
module procedure num2str_int
module procedure num2str_real
end interface
contains
function num2str_int(number)
implicit none
integer,intent(in) :: number
character(len=6) :: num2str_int
character(len=6) :: tmp
write(tmp,'(I6)')number
num2str_int = tmp
end function
function num2str_real(number)
implicit none
real,intent(in) :: number
character(len=6) :: num2str_real
character(len=6) :: tmp
write(tmp,'(F6.4)')number
num2str_real = tmp
end function
end module
program test_strings
use strings
write(*,*) num2str(1)//' '//num2str(1.23)
end program
这篇关于创建一个用于消息记录的重载函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!