Keyboard input/Obtain a Y or N response: Difference between revisions
Content added Content deleted
m (→{{header|PureBasic}}: Cleaned up code & improved comments) |
(→Tcl: Added implementation) |
||
Line 30: | Line 30: | ||
Until Key$="Y" Or Key$="N" |
Until Key$="Y" Or Key$="N" |
||
PrintN("The response was "+Key$)</lang> |
PrintN("The response was "+Key$)</lang> |
||
=={{header|Tcl}}== |
|||
<lang tcl>proc yesno {{message "Press Y or N to continue"}} { |
|||
fconfigure stdin -blocking 0 |
|||
exec stty raw |
|||
read stdin ; # flush |
|||
puts -nonewline "${message}: " |
|||
flush stdout |
|||
while {![eof stdin]} { |
|||
set c [string tolower [read stdin 1]] |
|||
if {$c eq "y" || $c eq "n"} break |
|||
} |
|||
puts [string toupper $c] |
|||
exec stty -raw |
|||
fconfigure stdin -blocking 1 |
|||
return [expr {$c eq "y"}] |
|||
} |
|||
set yn [yesno "Do you like programming (Y/N)"]</lang> |
Revision as of 16:29, 15 October 2010
Keyboard input/Obtain a Y or N response is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.
Obtain a valid Y or N response from the keyboard. The keyboard should be flushed, so that any outstanding keypresses are removed, preventing any exiting Y or N keypress from being evaluated. The response should be obtained as soon as Y or N are pressed, and there should be no need to press an enter key.
BASIC
ZX Spectrum Basic
10 IF INKEY$<>"" THEN GOTO 10 20 PRINT "Press Y or N to continue" 30 LET k$ = INKEY$ 40 IF k$ = "y" OR k$ = "Y" OR k$ = "n" OR k$ = "N" THEN GOTO 60 50 GOTO 30 60 PRINT "The response was "; k$
PureBasic
Inkey() returns the character string of the key which is being pressed at the time. <lang PureBasic>PrintN("Press Y or N to continue")
Repeat
; Get the key being pressed, or a empty string. Key$=UCase(Inkey()) ; ; To Reduce the problems with an active loop ; a Delay(1) will release the CPU for the rest ; of this quanta if no key where pressed. Delay(1)
Until Key$="Y" Or Key$="N" PrintN("The response was "+Key$)</lang>
Tcl
<lang tcl>proc yesno Template:Message "Press Y or N to continue" {
fconfigure stdin -blocking 0 exec stty raw read stdin ; # flush puts -nonewline "${message}: " flush stdout while {![eof stdin]} { set c [string tolower [read stdin 1]] if {$c eq "y" || $c eq "n"} break } puts [string toupper $c] exec stty -raw fconfigure stdin -blocking 1 return [expr {$c eq "y"}]
}
set yn [yesno "Do you like programming (Y/N)"]</lang>