我正在编写一个模拟ATM机工作的程序。基本上,如果输入无效字符,我想显示错误消息。例如:
'Please enter your name...'
[here user enters a random **digit**, which is not a character]
[here I want the program to **determine** whether the input type is
*character* or *integer* and then decide what to do next :
show an error or continue running]
我只是想知道是否有可能这样做?
有两件事。更容易的是查看是否有人输入了数字。Read 将尝试将输入的值放入提供的变量中,如果无法做到这一点,它将iostat
参数设置为正数:
program determine
implicit none
integer :: iNumber
integer :: io_stat
do
print *, "Please enter a number"
read(*, *, iostat=io_stat) iNumber
if (io_stat == 0) exit
print *, "This isn't a number, try again!"
end do
print *, "You entered a number ", iNumber
end program determine
当然,另一种方式并不容易。"Hello"从来都不是整数,但"12"肯定是字符串。因此,在这种情况下,您必须直接验证字符串。一个简单、快速和肮脏的解决方案是这样的:
program determine
implicit none
character(len=50) :: cName
do
print *, "Please enter a name: (A-Za-z)"
read(*, '(A50)') cName
if (valid_input(cName)) exit
print *, "No valid input! Try again!"
end do
print *, "You entered the name " // trim(cName)
contains
function valid_input(cName)
implicit none
character(len=*), intent(in) :: cName
logical :: valid_input
integer :: i
valid_input = .false.
if (len_trim(cName) == 0) return
do i = 1, len_trim(cName)
select case(ichar(cName(i:i)))
case(ichar('A'):ichar('Z'))
continue
case(ichar('a'):ichar('z'))
continue
case default
return
end select
end do
valid_input = .true.
end function valid_input
end program determine
更新:正如@francescalus在此答案的评论中指出的那样,您还可以使用 VERIFY
关键字来检查字符串中是否存在不一致的字符。当然,这意味着您必须在SET
字符串中输入每个符合要求的字母,但它仍然比我的valid_input
方法短:
function valid_input(cName)
implicit none
character(len=*), intent(in) :: cName
logical :: valid_input
valid_input = &
( ( len_trim(cName) > 0 ) .and. &
( verify(trim(cName), &
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' // &
'abcdefghijklmnopqrstuvwxyz' &
) == 0 &
) &
)
end function valid_input
当然,这不会验证包含空格或其他非标准字母的名称。如果你需要更复杂的东西,你几乎已经到了想要实现正则表达式的地步。有关示例,请参阅此处。