2016-10-25 53 views
4

我有一个交互式FORTRAN程序,需要来自用户的各种输入。现在,我想将此Fortran程序的输出存储到变量中,并在shell脚本中使用此值。我试过将Fortran程序输出到变量中

var=`./test` and var=$(./test) 

但是在这两种情况下,它都不会提示用户输入并保持空闲状态。我该怎么办? 一块的例子Fortran代码是这样的

test.f 

    program test 
    character*1 resp1, resp3 
    integer resp2, ans 

    write(*,*) 'Think of a prime number less than 10' 
    write(*,*) 'Say whether it is odd or even' 
    write(*,*) 'Write o/e' 
    read(*,*) resp1 
    if (resp1 .EQ. 'e') then 
    ans=2 
    else 
    write(*,*) 'Is the number close to 4 or 8' 
    read (*,*) resp2 
    if (resp2 == 8) then 
    ans=7 
    else 
    write(*,*) 'Is the number greater than or less than 4' 
    write(*,*) 'Write g or l' 
    read (*,*) resp3 
    if (resp3 .EQ. 'l') then 
    ans=3 
    else 
    ans=5 
    end if 
    end if 
    end if 
    write(*,*) ans 
    end 

    Compiled as gfortran test.f -o test 

然后我用一个这样的脚本

test.sh 

var=`./test` 
echo "The answer you are looking for is " $var 

我相信有一些很琐碎,我无法找到。请帮帮我。

P.S.这只是一个示例代码和脚本,而我的实际脚本和代码则完全不同。

+2

提示输出和变量输出合并。不知道这是否可能,但你能提示用户标准错误而不是标准输出吗?这将工作。 –

+0

让我试试。你的意思是使用$? ? –

+0

我强烈建议您编写自由格式的Fortran。请参阅:http://www.fortran90.org/src/best-practices.html – jlokimlin

回答

3

让 - 弗朗索瓦法布尔是对的。

program test 
character*1 resp1, resp3 
integer resp2, ans 

write(0,*) 'Think of a prime number less than 10' 
write(0,*) 'Say whether it is odd or even' 
write(0,*) 'Write o/e' 
read(5,*) resp1 
if (resp1 .EQ. 'e') then 
ans=2 
else 
write(0,*) 'Is the number close to 4 or 8' 
read (5,*) resp2 
if (resp2 == 8) then 
    ans=7 
else 
    write(0,*) 'Is the number greater than or less than 4' 
    write(0,*) 'Write g or l' 
    read (5,*) resp3 
    if (resp3 .EQ. 'l') then 
    ans=3 
    else 
    ans=5 
    end if 
end if 
end if 
write(6,*) ans 
end 

问题是标准错误(0),答案是标准输入(5),结果是标准输出(6)

var=`./test` 

之后正常工作。

+0

0,5和6?出于好奇,1,2,3和4是什么? –

+1

非常感谢。有用。我总是用写(*,*)。我今天意识到内部数字的重要性。 –

+1

@JamesBrown:据我所知,他们可以被定义为文件。 0,5和6只是一个古老的惯例,几乎和Fortran中的其他一切一样:D https://en.wikipedia.org/wiki/Standard_streams –