2016-10-25 52 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 –