fortran - 在 Fortran 中解析随机 "String + Integers"

标签 fortran fortran90 fortran95

假设我想解析以下字符串:

Fortran 90 中的“计算(整数)和(整数)之和”,我无法知道整数有多大。可以是 3,也可以是 300,000。

据我所知,FORMAT 语句没有留下在运行时推断整数大小的空间。对于小至 3 的数字,选择太大的尺寸(例如 i5),程序就会崩溃。

我最好如何解决这个问题?

最佳答案

如果在编译时已知整数在字符串中的位置(例如第 5 个和第 7 个单词),我们可以使用列表定向读取直接获取整数:

character(256) :: line, words( 50 )
integer :: i1, i2

line = "Compute the sum of 3 and 30000, then we get..."

read( line, * ) words( 1 : 7 )   !! get the first seven words from a line
read( words( 5 ), * ) i1         !! convert the 5th and 7th words to integer
read( words( 7 ), * ) i2         !! so that i1 = 3, i2 = 30000

但是如果整数的位置未知(例如,当从用户输入获取时),事情可能会更复杂......我为此编写了一些子例程,所以如果它看起来有用,请尝试一下:)

module strmod
contains

subroutine split ( line, words, nw )
    implicit none
    character(*), intent(in)  :: line
    character(*), intent(out) :: words(:)
    integer,      intent(out) :: nw
    character(len(words)) :: buf( size(words) )
    integer :: k, ios

    nw = 0 ; words(:) = ""

    do k = 1, size(words)
        read( line, *, iostat=ios ) buf( 1 : k )
        if ( ios /= 0 ) exit
        nw = k
        words( 1 : nw ) = buf( 1 : nw )
    enddo

endsubroutine

subroutine words_to_ints ( words, ints, ni )
    implicit none
    character(*), intent(in)  :: words(:)
    integer,      intent(out) :: ints(:)
    integer,      intent(out) :: ni
    integer :: k, val, ios

    ni = 0 ; ints(:) = 0

    do k = 1, size(words)
        read( words( k ), *, iostat=ios ) val
        if ( ios /= 0 ) cycle
        ni = ni + 1
        if ( ni > size(ints) ) stop "size(ints) too small"
        ints( ni ) = val
    enddo

endsubroutine

endmodule

program main
    use strmod
    implicit none
    character(80) :: line, words( 50 )  !! works also with size 5 or 7 etc
    integer :: ints( 50 ), nw, ni, k

    line = "Compute the sum of 3 and 30000, then we get 300003 (no!!)"
            !... Note: spaces and commas serve as delimiters. Better to avoid "/".

    call split ( line, words, nw )
    call words_to_ints ( words, ints, ni )

    print *, "Word counts:", nw
    do k = 1, nw
        print *, trim( words( k ) )
    enddo

    print *, "Int counts:", ni
    print *, ints( 1 : ni )
end

结果:

Word counts:          12
Compute
the
sum
of
3
and
30000
then
we
get
300003
(no!!)
Int counts:           3
       3       30000      300003

关于fortran - 在 Fortran 中解析随机 "String + Integers",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33446560/

相关文章:

arrays - 按列将数组写入文件

fortran - OpenMP 竞争条件(Fortran 77 w/COMMON block )

python-2.7 - 如何在 Python 中读取 Fortran 固定宽度格式的文本文件?

format - 从fortran中的txt文件读取数据

emacs - 我可以使用固定格式的 emacs f90-mode 吗?

fortran - 使用 MPI IO 编写多个分布式数组

fortran - 在 fortran 中用零填充数组而不使用循环

arrays - 数组排序算法的问题

fortran - 将字符串内联传递给子例程调用(其中参数已定义长度)会产生意外结果

arrays - Fortran:普通数组与存储相同数据量的对象所需的 RAM