fortran 77从输入到字符串,如java中的input.next()
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了fortran 77从输入到字符串,如java中的input.next()相关的知识,希望对你有一定的参考价值。
我是Fortran 77上的新手。我需要一个类似于Java中的input.next()的代码。我想给出一个像“你好今天怎么样”的输入,并逐一检查每个单词,所以要做到这一点,我需要逐个说出来。最简单的方法是什么?我可以检查每个字符并在字符变量中将字符放在空格之前,但它看起来很难。
答案
虽然这可能是重复的,但这就是我手头的东西(为了表明没有直接的内置例程,虽然它看起来可能看起来很棘手,但是以某种方式编写它并不“难”......)我认为还有更有效的方法基于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=
以上是关于fortran 77从输入到字符串,如java中的input.next()的主要内容,如果未能解决你的问题,请参考以下文章