[英]Fortran77 User Input Validation
I need the user to enter only real numbers when prompted. 提示时,我只需要用户输入实数。 An error message should be displayed and program should stop in case the user enters a character or any other symbol.
如果用户输入一个字符或任何其他符号,应显示一条错误消息并停止程序。 How can i do this in fortran 77.
我该如何在fortran 77中执行此操作。
I assumed, you probably want to have more tries, because what you have in your question does the compiler does automatically. 我假设,您可能想尝试更多,因为问题中的内容是编译器自动执行的。
You can use the IOSTAT=
or ERR=
specifiers. 您可以使用
IOSTAT=
或ERR=
说明符。
INTEGER IE
DO I = 1, MAX
READ(*,*,IOSTAT=IE) X
IF (IE.eq.0) GOTO 10
PRINT *,"Wrong input, try again."
END DO
10 CONTINUE
or 要么
GOTO 10
20 PRINT *,"Wrong input, try again."
10 READ(*,*,ERR=20) X
improving the user interface a little, i like to read a string, then do the error check on an internal read: 稍微改善用户界面,我喜欢读取一个字符串,然后对内部读取进行错误检查:
character insting*80
ie=1
do while(ie.ne.0)
read(*,'(a)')instring
if(instring(1:1).eq.'q')stop
read(instring,*,iostat=ie)x
if(ie.ne.0)then
write(*,*)'invalid input ',trim(instring),' is not a real number'
endif
enddo
(note trim
is not f77 btw, but its easy enough to replicate if needed) (请注意,
trim
不是f77 btw,但是如果需要的话,可以轻松复制)
Note, with some effort you can handle the pathalogic cases. 请注意,您可以通过一些努力来处理病理病例。 A leading '/' or ',' throws no error but leaves the value of x unchanged (likely system/compiler dependent however!), so you can do something like this:
前导'/'或','不会引发错误,但x的值保持不变(不过可能取决于系统/编译器!),因此您可以执行以下操作:
x=-999999.
read(instring,*,iostat=ie)x
if(ie.eq.0.and.x.eq.-999999.)then
.. code to handle error..
endif
You could alternately use index
to look for the bad characters. 您可以选择使用
index
查找不良字符。 On my system a decimal .
在我的系统上,十进制
.
by itself is taken as zero. 本身被视为零。 That gets a bit cumbersome to handle, but it can be done by parsing
instring
处理起来有点麻烦,但是可以通过解析
instring
来完成
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.