fortran 77从输入到字符串,如java中的input.next()

问题描述 投票:-3回答:1

我是Fortran 77上的新手。我需要一个类似于Java中的input.next()的代码。我想给出一个像“你好今天怎么样”的输入,并逐一检查每个单词,所以要做到这一点,我需要逐个说出来。最简单的方法是什么?我可以检查每个字符并在字符变量中将字符放在空格之前,但它看起来很难。

input fortran fortran77
1个回答
2
投票

虽然这可能是重复的,但这就是我手头的东西(为了表明没有直接的内置例程,虽然它看起来可能看起来很棘手,但是以某种方式编写它并不“难”......)我认为还有更有效的方法基于index()函数。如果有必要,编写类似“input_next()”的类似例程来逐个获取下一个单词[*]可能会很有用。

program main
    implicit none
    character(100) line, words( 100 )
    integer n, i

    line = "hi how are you today"   ! input string
    words = ""                      ! words to be obtained

    call split_str( line, words, n )

    do i = 1, n
        print *, "i= ", i, "word= ", trim(words( i ))
    enddo
end

subroutine split_str( line, words, n )
    implicit none
    character(*), intent(in)  :: line
    character(*), intent(out) :: words(*)
    integer,      intent(out) :: n
    integer :: ios
    character(100) :: buf( 100 )  ! large buffer

    n = 0
    do
        n = n + 1
        read( line, *, iostat=ios ) buf( 1 : n )  ! use list-directed input
        if ( ios == 0 ) then
            words( 1 : n ) = buf( 1 : n )   ! if success, copy to the original array
        else
            n = n - 1
            exit       ! if all the words are obtained, finish
        endif
    enddo
end

结果:

 i=            1 word= hi
 i=            2 word= how
 i=            3 word= are
 i=            4 word= you
 i=            5 word= today

[*]以下是这种getnextword()的一种可能方法,它通过列表导向输入从输入字符串(line)获取一个单词,并从字符串中删除该单词以进行下一次调用。如果在line中找不到更多单词,found将变为false。 (请在网上或SO页面中搜索“列表导向输入”以获取更多详细信息。)

program main
    implicit none
    character(100) line, word
    logical found

    line = "hi how are you today"
    do
        call getnextword( line, word, found )
        if ( .not. found ) exit
        print "(a,a7,2a)", "word= ", trim( word ), " : line= ", trim( line )
    enddo
end program

subroutine getnextword( line, word, found )
    implicit none
    character(*), intent(inout) :: line
    character(*), intent(out)   :: word
    logical,      intent(out)   :: found
    integer :: ios
    character(100) :: buf

    read( line, *, iostat=ios ) buf   ! try to read one word into a buffer via list-directed input

    if ( ios == 0 ) then       ! if success
        found = .true.
        word = trim( buf )      ! save the word
        line = adjustL( line )
        line = line( len_trim( word ) + 1 : )   ! and remove the word from the input line
    else
        found = .false.
        word = ""
    endif
end

结果:

word=      hi : line=  how are you today
word=     how : line=  are you today
word=     are : line=  you today
word=     you : line=  today
word=   today : line= 
© www.soinside.com 2019 - 2024. All rights reserved.