处理FORTRAN中的用户输入类型不匹配 [英] Handle user input type mismatch in FORTRAN
问题描述
我正在Silverfrost FTN5中构建一个基本程序,其中我从用户那里输入了一个整数.
如果用户输入浮点值,则会引发错误,程序结束.有什么方法可以处理此无效输入并要求用户输入有效输入?
I am building a basic program in Silverfrost FTN5 wherein I input an integer from user.
If user enters a float value, it throws an error and the program ends. Is there any way I can handle this invalid input and ask user to enter valid input?
推荐答案
有几种方法. 1)将输入读入字符串并解析该字符串.如果字符串包含句点,则拒绝它并重新询问输入.如果字符串看起来有效,请从字符串read (string, *) IntVal
进行内部"读取整数. 2)更健壮,因为这可以正常检测所有错误:在read语句中使用IOSTAT=
关键字.如果该值不为零,则出现错误...请重新输入.
There are several methods. 1) Read the input into a string and parse the string. If the string contains a period, reject it and re-ask for input. If the string appears valid, do an "internal" read of the integer from the string: read (string, *) IntVal
. 2) More robust since this gracefully detects all errors: use the IOSTAT=
keyword in your read statement. If the value is non-zero, there was an error ... re-ask for input.
代码示例:
program TestRead
integer :: number, ReadStatus
write (*, '( "Input integer: " )', advance="no" )
ReadInt: do
read (*, *, iostat=ReadStatus) number
if ( ReadStatus == 0 ) then
exit ReadInt
else
write (*, '( / "READ ERROR: please re-input:" )' )
end if
end do ReadInt
write (*, '( / "Value read: ", I0 )' ) number
end program TestRead
这篇关于处理FORTRAN中的用户输入类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!