Keyboard input/Obtain a Y or N response: Difference between revisions
MaiconSoft (talk | contribs) No edit summary |
Add SmallBASIC |
||
(27 intermediate revisions by 18 users not shown) | |||
Line 10: | Line 10: | ||
The response should be obtained as soon as '''Y''' or '''N''' are pressed, and there should be no need to press an enter key. |
The response should be obtained as soon as '''Y''' or '''N''' are pressed, and there should be no need to press an enter key. |
||
<br><br> |
<br><br> |
||
=={{header|8080 Assembly}}== |
|||
This program uses CP/M to read the keyboard. |
|||
<syntaxhighlight lang="8080asm">rawio: equ 6 ; Raw console input |
|||
puts: equ 9 ; String output |
|||
bdos: equ 5 ; CP/M entry point |
|||
org 100h |
|||
jmp demo |
|||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
|||
;;; Routine: read 'Y' or 'N' from the keyboard. |
|||
;;; Output: carry flag clear if Y pressed, set if N pressed. |
|||
yesno: mvi c,rawio ; Read input from console |
|||
mvi e,-1 |
|||
call bdos |
|||
ana a ; Read keys as long as a key is pressed |
|||
jnz yesno ; (wait until keyboard is clear) |
|||
yread: mvi c,rawio ; Then, wait for a key to be pressed |
|||
mvi e,-1 |
|||
call bdos |
|||
ana a |
|||
jz yread |
|||
ori 32 ; Set bit 5 to make input letters lowercase |
|||
cpi 'y' ; If the key is Y, |
|||
rz ; then return (carry is clear here) |
|||
cpi 'n' ; If the key is N, |
|||
stc ; then set the carry flag and return |
|||
rz |
|||
jmp yread ; If it wasn't Y or N, get another key |
|||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
|||
;;; Demo code: use the routine to read Y or N, and then print |
|||
;;; 'yes' or 'no'. |
|||
demo: call yesno ; Read Y or N |
|||
mvi c,puts |
|||
lxi d,yes |
|||
jnc bdos ; If carry clear, print 'Yes' |
|||
lxi d,no |
|||
jmp bdos ; Otherwise, print 'No' |
|||
yes: db 'Yes$' |
|||
no: db 'No$'</syntaxhighlight> |
|||
=={{header|8086 Assembly}}== |
|||
{{works with|MS-DOS}} |
|||
;Assembled using UASM v2.49 |
|||
<syntaxhighlight lang="asm"> .model small |
|||
.stack 1024 |
|||
.data |
|||
;no data needed |
|||
.code |
|||
start: |
|||
mov ax,@code |
|||
mov ds,ax |
|||
call PRIMM |
|||
BYTE "Exit program and return to MS-DOS? (Y/N)",0 |
|||
mov ax,0C00h |
|||
int 21h ;flush keyboard buffer |
|||
forever: |
|||
call waitKey |
|||
;returns ASCII code in AL |
|||
and AL,11011111b ;ignore case |
|||
cmp al,"Y" |
|||
jz ReturnToMSDOS |
|||
cmp al,"N" |
|||
jz forever |
|||
;normally this would jump somewhere else but for simplicity it will wait |
|||
;for a yes response. |
|||
jnz forever |
|||
ReturnToMSDOS: |
|||
mov ax,0C00h |
|||
int 21h ;flush keyboard buffer |
|||
mov ax,4C00h |
|||
int 21h ;end program |
|||
;------------------------------------------------------------------- |
|||
; SUBROUTINES |
|||
;------------------------------------------------------------------- |
|||
waitKey: |
|||
mov ah,01h |
|||
int 16h |
|||
jz waitKey |
|||
ret |
|||
;waits until a key is pressed. |
|||
;return: |
|||
; AL = ASCII CODE |
|||
; AH = SCAN CODE (???) |
|||
;------------------------------------------------------------------- |
|||
PrintString: ;Print null-terminated strings |
|||
;input: string address = ds:si |
|||
lodsb ;Load a letter |
|||
cmp al,0 ;Was that letter the terminator? |
|||
jz PrintString_Done ;Yes? then RET |
|||
call PrintChar ;Print to screen |
|||
jmp PrintString ;Repeat |
|||
PrintString_Done: |
|||
ret |
|||
;------------------------------------------------------------------- |
|||
PrintChar: |
|||
push ax |
|||
mov ah,0Eh |
|||
int 10h ;print AL to the screen. |
|||
pop ax |
|||
ret |
|||
;------------------------------------------------------------------- |
|||
PrintSpace: |
|||
mov al,' ' |
|||
jmp PrintChar ;JMP avoids a tail call. |
|||
;ret ;"PrintChar"'s ret will do this for us. |
|||
;------------------------------------------------------------------- |
|||
NewLine: |
|||
push dx |
|||
push ax |
|||
mov ah, 02h |
|||
mov dl, 13 ;CR |
|||
int 21h |
|||
mov dl, 10 ;LF |
|||
int 21h |
|||
pop ax |
|||
pop dx |
|||
ret |
|||
;------------------------------------------------------------------- |
|||
PRIMM: |
|||
pop si |
|||
push ax |
|||
;get return address in si, this is the source offset for |
|||
;the string that will be printed. |
|||
;String must be null terminated. |
|||
call PrintString |
|||
pop ax |
|||
push si |
|||
;PrintString adjusts the return address for us, it is now |
|||
;just after the null terminator. So put it back on the stack. |
|||
ret |
|||
;------------------------------------------------------------------- |
|||
end start</syntaxhighlight> |
|||
=={{header|8th}}== |
=={{header|8th}}== |
||
< |
<syntaxhighlight lang="forth"> |
||
\ get a yes or no response from the keyboard |
\ get a yes or no response from the keyboard |
||
: yes-no |
: yes-no |
||
Line 23: | Line 176: | ||
"Yes or no? " con:print yes-no no? |
"Yes or no? " con:print yes-no no? |
||
cr bye |
cr bye |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Action!}}== |
|||
<syntaxhighlight lang="action!">PROC MAIN() |
|||
Byte Key=764 |
|||
Printe("Press Y or N to continue") |
|||
key=255 |
|||
Do |
|||
Until Key=43 or Key=35 |
|||
Od |
|||
Print("You pressed ") |
|||
If Key=43 then Printe("Yes") Fi |
|||
If Key=35 then Printe("No ") Fi |
|||
RETURN</syntaxhighlight> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
< |
<syntaxhighlight lang="ada"> function Yes_Or_No (Prompt : String := "Your answer (Y/N): ") return Boolean is |
||
Answer : Character; |
Answer : Character; |
||
begin |
begin |
||
Line 39: | Line 210: | ||
end case; |
end case; |
||
end loop; |
end loop; |
||
end Yes_Or_No;</ |
end Yes_Or_No;</syntaxhighlight> |
||
=={{header|AutoHotkey}}== |
=={{header|AutoHotkey}}== |
||
< |
<syntaxhighlight lang="autohotkey">Loop, { |
||
Input, Key, L1 |
Input, Key, L1 |
||
if (Key = "n" || Key = "y") |
if (Key = "n" || Key = "y") |
||
Line 48: | Line 219: | ||
} |
} |
||
MsgBox, % "The response was """ Key """." |
MsgBox, % "The response was """ Key """." |
||
ExitApp</ |
ExitApp</syntaxhighlight> |
||
=={{header|AWK}}== |
=={{header|AWK}}== |
||
<syntaxhighlight lang="awk"> |
|||
<lang AWK> |
|||
# syntax: GAWK -f KEYBOARD_INPUT_OBTAIN_A_Y_OR_N_RESPONSE.AWK |
# syntax: GAWK -f KEYBOARD_INPUT_OBTAIN_A_Y_OR_N_RESPONSE.AWK |
||
BEGIN { |
BEGIN { |
||
Line 69: | Line 240: | ||
return(rec) |
return(rec) |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 78: | Line 249: | ||
=={{header|Axe}}== |
=={{header|Axe}}== |
||
Since the TI-83/84 require a modifier key to access the letters, this example uses the 2nd key as Y and the Clear key as N. |
Since the TI-83/84 require a modifier key to access the letters, this example uses the 2nd key as Y and the Clear key as N. |
||
< |
<syntaxhighlight lang="axe">While getKey(0) |
||
End |
End |
||
Line 89: | Line 260: | ||
Return |
Return |
||
End |
End |
||
End</ |
End</syntaxhighlight> |
||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
Line 95: | Line 266: | ||
==={{header|Applesoft BASIC}}=== |
==={{header|Applesoft BASIC}}=== |
||
< |
<syntaxhighlight lang="applesoftbasic">10 LET C = PEEK (49168): REM CLEAR KEYBOARD |
||
20 PRINT "PRESS Y OR N TO CONTINUE" |
20 PRINT "PRESS Y OR N TO CONTINUE" |
||
30 GET K$ |
30 GET K$ |
||
40 IF K$ < > "Y" AND K$ < > "N" THEN 30 |
40 IF K$ < > "Y" AND K$ < > "N" THEN 30 |
||
50 PRINT "THE RESPONSE WAS ";K$ |
50 PRINT "THE RESPONSE WAS ";K$ |
||
</syntaxhighlight> |
|||
</lang> |
|||
==={{header|BASIC256}}=== |
|||
<syntaxhighlight lang="freebasic">print "Do you want to continue y/n : "; |
|||
do |
|||
KBD$ = key |
|||
until KBD$ = "89" or KBD$ = "78" |
|||
print chr(KBD$) |
|||
if KBD$ = "89" then |
|||
print "OK, continuing" |
|||
else |
|||
print "OK, finishing" |
|||
end if</syntaxhighlight> |
|||
==={{header|QBasic}}=== |
|||
<syntaxhighlight lang="qbasic">PRINT "Press Y or N to continue." |
|||
DO |
|||
KBD$ = "" |
|||
WHILE KBD$ = "" |
|||
KBD$ = UCASE$(INKEY$) |
|||
WEND |
|||
IF KBD$ <> "Y" AND KBD$ <> "N" THEN BEEP |
|||
LOOP UNTIL KBD$ = "Y" OR KBD$ = "N" |
|||
PRINT "The response was "; KBD$</syntaxhighlight> |
|||
==={{header|BBC BASIC}}=== |
==={{header|BBC BASIC}}=== |
||
< |
<syntaxhighlight lang="bbcbasic"> REPEAT UNTIL INKEY$(0) = "" |
||
PRINT "Press Y or N to continue" |
PRINT "Press Y or N to continue" |
||
REPEAT |
REPEAT |
||
key$ = GET$ |
key$ = GET$ |
||
UNTIL key$="Y" OR key$="N" |
UNTIL key$="Y" OR key$="N" |
||
PRINT "The response was " key$</ |
PRINT "The response was " key$</syntaxhighlight> |
||
==={{header|Commodore BASIC}}=== |
==={{header|Commodore BASIC}}=== |
||
< |
<syntaxhighlight lang="basic">10 PRINT "PRESS Y OR N TO CONTINUE:"; |
||
20 POKE 198, 0: REM CLEAR KEY BUFFER |
20 POKE 198, 0: REM CLEAR KEY BUFFER |
||
30 GET K$ |
30 GET K$ |
||
40 IF K$ <> "Y" AND K$ <> "N" THEN 30 |
40 IF K$ <> "Y" AND K$ <> "N" THEN 30 |
||
50 PRINT K$</ |
50 PRINT K$</syntaxhighlight> |
||
Note that 198 is the location of the keyboard buffer index on the VIC-20, C-64, and C-128. On the PET, the correct location is 158, while on the Plus/4 and C-16, it's 239. |
Note that 198 is the location of the keyboard buffer index on the VIC-20, C-64, and C-128. On the PET, the correct location is 158, while on the Plus/4 and C-16, it's 239. |
||
Line 120: | Line 317: | ||
The loop on lines 30 - 40 will cycle as fast as the interpreter can go, assigning K$ the empty string until the user presses a key. On versions of BASIC later than the 2.0 on the VIC and 64 (e.g. 3.5 on the C-16 and Plus/4, 7.0 on the C-128), GETKEY may be used in place of GET. GETKEY will wait for the user to press a key before continuing, so the polling is done in the BASIC interpreter's machine language code, and the BASIC loop only cycles when the user presses a key other than Y or N. |
The loop on lines 30 - 40 will cycle as fast as the interpreter can go, assigning K$ the empty string until the user presses a key. On versions of BASIC later than the 2.0 on the VIC and 64 (e.g. 3.5 on the C-16 and Plus/4, 7.0 on the C-128), GETKEY may be used in place of GET. GETKEY will wait for the user to press a key before continuing, so the polling is done in the BASIC interpreter's machine language code, and the BASIC loop only cycles when the user presses a key other than Y or N. |
||
==={{header| |
==={{header|GW-BASIC}}=== |
||
{{works with|QBasic}} |
|||
< |
<syntaxhighlight lang="gwbasic">10 CLS: PRINT "Press Y or N to continue." |
||
20 WHILE T$<>"y" AND T$<>"Y" AND T$<>"n" AND T$<>"N" |
20 WHILE T$<>"y" AND T$<>"Y" AND T$<>"n" AND T$<>"N" |
||
30 T$="" |
30 T$="" |
||
Line 131: | Line 328: | ||
80 WEND |
80 WEND |
||
90 PRINT "The response was "; T$ |
90 PRINT "The response was "; T$ |
||
</syntaxhighlight> |
|||
</lang> |
|||
===={{header| |
===={{header|GW-BASIC variant}}==== |
||
<syntaxhighlight lang="gwbasic">10 DEF FNUP$(C$)=CHR$(ASC(C$)-32*(ASC(C$)>96)*(ASC(C$)<123)) |
|||
<lang gwbasic> |
|||
10 DEF FNUP$(C$)=CHR$(ASC(C$)-32*(ASC(C$)>96)*(ASC(C$)<123)) |
|||
20 CLS: PRINT "Press Y or N to continue." |
20 CLS: PRINT "Press Y or N to continue." |
||
30 WHILE T$<>"Y" AND T$<>"N" |
30 WHILE T$<>"Y" AND T$<>"N" |
||
Line 141: | Line 337: | ||
50 IF T$<>"Y" AND T$<>"N" THEN BEEP |
50 IF T$<>"Y" AND T$<>"N" THEN BEEP |
||
60 WEND |
60 WEND |
||
70 PRINT "The response was: "; T$ |
70 PRINT "The response was: "; T$</syntaxhighlight> |
||
</lang> |
|||
==={{header|IS-BASIC}}=== |
==={{header|IS-BASIC}}=== |
||
< |
<syntaxhighlight lang="is-basic">100 GET K$ ! Flush the keyboard buffer |
||
110 PRINT "Press Y or N to continue." |
110 PRINT "Press Y or N to continue." |
||
120 DO |
120 DO |
||
130 LET K$=LCASE$(INKEY$) |
130 LET K$=LCASE$(INKEY$) |
||
140 LOOP UNTIL K$="y" OR K$="n" |
140 LOOP UNTIL K$="y" OR K$="n" |
||
150 PRINT "The response was ";K$</ |
150 PRINT "The response was ";K$</syntaxhighlight> |
||
==={{header|Locomotive Basic}}=== |
==={{header|Locomotive Basic}}=== |
||
<syntaxhighlight lang="locobasic">10 CLEAR INPUT |
|||
<lang locobasic>10 CLEAR INPUT |
|||
20 PRINT "Press Y or N to continue" |
20 PRINT "Press Y or N to continue" |
||
30 a$=LOWER$(INKEY$) |
30 a$=LOWER$(INKEY$) |
||
Line 161: | Line 355: | ||
60 IF a$="n" THEN PRINT "No":END |
60 IF a$="n" THEN PRINT "No":END |
||
70 PRINT "Try again" |
70 PRINT "Try again" |
||
80 GOTO 30</ |
80 GOTO 30</syntaxhighlight> |
||
==={{header|True BASIC}}=== |
|||
<syntaxhighlight lang="qbasic">LIBRARY "DefLib.trc" |
|||
DECLARE DEF INKEY$ |
|||
PRINT "Press Y or N to continue." |
|||
DO |
|||
LET kbd$ = "" |
|||
DO WHILE kbd$ = "" |
|||
LET kbd$ = UCASE$(INKEY$) |
|||
LOOP |
|||
IF kbd$ <> "Y" AND kbd$ <> "N" THEN SOUND 800, .25 |
|||
LOOP UNTIL kbd$ = "Y" OR kbd$ = "N" |
|||
PRINT "The response was "; kbd$ |
|||
END</syntaxhighlight> |
|||
==={{header|SmallBASIC}}=== |
|||
<syntaxhighlight lang="qbasic"> |
|||
PRINT "Press Y or N key to continue" |
|||
WHILE(1) |
|||
k = INKEY |
|||
IF(k == "y" OR k == "n") THEN EXIT |
|||
SHOWPAGE |
|||
WEND |
|||
PRINT "The response was: "; upper(k) |
|||
</syntaxhighlight> |
|||
==={{header|Yabasic}}=== |
|||
<syntaxhighlight lang="yabasic">clear screen |
|||
print "Do you want to continue y/n : "; |
|||
repeat |
|||
KBD$ = lower$(inkey$) |
|||
until KBD$ = "y" or KBD$ = "n" |
|||
print KBD$ |
|||
if KBD$ = "y" then |
|||
print "OK, continuing" |
|||
else |
|||
print "OK, finishing" |
|||
end if</syntaxhighlight> |
|||
==={{header|ZX Spectrum Basic}}=== |
==={{header|ZX Spectrum Basic}}=== |
||
Note that this will also work in [[GW-BASIC]] and most [[QBasic]]-compatible BASICs if all instances of "<code>GO TO</code>" are changed to "<code>GOTO</code>". |
Note that this will also work in [[GW-BASIC]] and most [[QBasic]]-compatible BASICs if all instances of "<code>GO TO</code>" are changed to "<code>GOTO</code>". |
||
< |
<syntaxhighlight lang="qbasic">10 IF INKEY$<>"" THEN GO TO 10: REM flush the keyboard buffer |
||
20 PRINT "Press Y or N to continue" |
20 PRINT "Press Y or N to continue" |
||
30 LET k$ = INKEY$ |
30 LET k$ = INKEY$ |
||
40 IF k$ <> "y" AND k$ <> "Y" AND k$ <> "n" AND k$ <> "N" THEN GO TO 30 |
40 IF k$ <> "y" AND k$ <> "Y" AND k$ <> "n" AND k$ <> "N" THEN GO TO 30 |
||
50 PRINT "The response was "; k$</ |
50 PRINT "The response was "; k$</syntaxhighlight> |
||
=={{header|Batch File}}== |
=={{header|Batch File}}== |
||
< |
<syntaxhighlight lang="dos"> |
||
@echo off |
@echo off |
||
choice |
choice |
||
Line 179: | Line 417: | ||
if errorlevel 1 echo You chose Y |
if errorlevel 1 echo You chose Y |
||
>nul pause |
>nul pause |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|C}}== |
=={{header|C}}== |
||
For POSIX compliant systems (in theory that includes WinNT family). |
For POSIX compliant systems (in theory that includes WinNT family). |
||
<syntaxhighlight lang="c"> |
|||
<lang C> |
|||
#include <stdio.h> |
#include <stdio.h> |
||
#include <termios.h> |
#include <termios.h> |
||
Line 246: | Line 484: | ||
return 0; |
return 0; |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C sharp}}== |
=={{header|C sharp}}== |
||
< |
<syntaxhighlight lang="c sharp">using System; |
||
namespace Y_or_N |
namespace Y_or_N |
||
Line 284: | Line 522: | ||
} |
} |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|C++}}== |
=={{header|C++}}== |
||
Windows specific |
Windows specific |
||
< |
<syntaxhighlight lang="cpp">#include <conio.h> |
||
#include <iostream> |
#include <iostream> |
||
Line 313: | Line 551: | ||
return 0; |
return 0; |
||
} |
} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Clojure}}== |
=={{header|Clojure}}== |
||
Line 323: | Line 561: | ||
< |
<syntaxhighlight lang="clojure"> |
||
(ns yprompt.core |
(ns yprompt.core |
||
(:import jline.Terminal) |
(:import jline.Terminal) |
||
Line 341: | Line 579: | ||
(defn -main [& args] |
(defn -main [& args] |
||
(prompt)) |
(prompt)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |
||
Line 349: | Line 587: | ||
Version 1: |
Version 1: |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun rosetta-y-or-n () |
(defun rosetta-y-or-n () |
||
(clear-input *query-io*) |
(clear-input *query-io*) |
||
(y-or-n-p)) |
(y-or-n-p)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Version 2: |
Version 2: |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun y-or-n () |
(defun y-or-n () |
||
(clear-input *standard-input*) |
(clear-input *standard-input*) |
||
Line 365: | Line 603: | ||
when q do (format t "~%Need Y or N~%") |
when q do (format t "~%Need Y or N~%") |
||
unless q return (if (equal c #\y) 'yes 'no))) |
unless q return (if (equal c #\y) 'yes 'no))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
Version 1 and 2 work as required in a LispWorks GUI interface, i.e. they return immediately when the y or n keys are pressed, without waiting for the Enter key. |
Version 1 and 2 work as required in a LispWorks GUI interface, i.e. they return immediately when the y or n keys are pressed, without waiting for the Enter key. |
||
Line 377: | Line 615: | ||
Version 3: |
Version 3: |
||
< |
<syntaxhighlight lang="lisp"> |
||
(defun y-or-no () |
(defun y-or-no () |
||
(with-screen (scr :input-buffering nil :input-blocking t) |
(with-screen (scr :input-buffering nil :input-blocking t) |
||
Line 386: | Line 624: | ||
((#\Y #\y) (return-from event-case t)) |
((#\Y #\y) (return-from event-case t)) |
||
((#\N #\n) (return-from event-case nil))))) |
((#\N #\n) (return-from event-case nil))))) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|D}}== |
=={{header|D}}== |
||
< |
<syntaxhighlight lang="d">import std.stdio: stdout, write, writefln; |
||
extern (C) nothrow { |
extern (C) nothrow { |
||
Line 415: | Line 653: | ||
writefln("\nResponse: %c", cast(char)c); |
writefln("\nResponse: %c", cast(char)c); |
||
_STD_conio(); |
_STD_conio(); |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Enter Y or N: abcN |
<pre>Enter Y or N: abcN |
||
Line 421: | Line 659: | ||
=={{header|Delphi}}== |
=={{header|Delphi}}== |
||
{{libheader| System.Console}} Thanks for JensBorrisholt [https://github.com/JensBorrisholt/DelphiConsole]. |
{{libheader| System.Console}} Thanks for JensBorrisholt [https://github.com/JensBorrisholt/DelphiConsole]. |
||
<syntaxhighlight lang="delphi"> |
|||
<lang Delphi> |
|||
program Obtain_a_Y_or_N_response; |
program Obtain_a_Y_or_N_response; |
||
Line 456: | Line 694: | ||
end; |
end; |
||
Readln; |
Readln; |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Press Y ou N |
<pre>Press Y ou N |
||
Line 464: | Line 702: | ||
{{Works with|EDT}} |
{{Works with|EDT}} |
||
{{Works with|RBD}} |
{{Works with|RBD}} |
||
< |
<syntaxhighlight lang="egl">handler YesOrNoHandler type RUIhandler{initialUI =[ui], onConstructionFunction = start} |
||
ui Div { }; |
ui Div { }; |
||
Line 488: | Line 726: | ||
end |
end |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Elm}}== |
=={{header|Elm}}== |
||
< |
<syntaxhighlight lang="elm">import Char |
||
import Graphics.Element exposing (Element, empty, show) |
import Graphics.Element exposing (Element, empty, show) |
||
import Keyboard |
import Keyboard |
||
Line 518: | Line 756: | ||
main : Signal Element |
main : Signal Element |
||
main = |
main = |
||
Signal.map view Keyboard.presses</ |
Signal.map view Keyboard.presses</syntaxhighlight> |
||
=={{header|ERRE}}== |
=={{header|ERRE}}== |
||
<syntaxhighlight lang="erre"> |
|||
<lang ERRE> |
|||
!$KEY |
!$KEY |
||
................ |
................ |
||
Line 544: | Line 782: | ||
PRINT("The response was ";K$) |
PRINT("The response was ";K$) |
||
................. |
................. |
||
</syntaxhighlight> |
|||
</lang> |
|||
<code>!$KEY </code> is a directive pragma: using it <code>GET</code> become an equivalent to Qbasic INKEY$, otherwise it's equivalent to QBasic INPUT$(1). !$KEY is also used to mantain portability with the C-64 version of ERRE language. |
<code>!$KEY </code> is a directive pragma: using it <code>GET</code> become an equivalent to Qbasic INKEY$, otherwise it's equivalent to QBasic INPUT$(1). !$KEY is also used to mantain portability with the C-64 version of ERRE language. |
||
=={{header|Euphoria}}== |
=={{header|Euphoria}}== |
||
< |
<syntaxhighlight lang="euphoria">integer key |
||
puts(1,"Your answer? (Y/N)\n") |
puts(1,"Your answer? (Y/N)\n") |
||
Line 561: | Line 799: | ||
end while |
end while |
||
printf(1,"Your response was %s\n",key)</ |
printf(1,"Your response was %s\n",key)</syntaxhighlight> |
||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp">open System |
||
let rec yorn () = |
let rec yorn () = |
||
Line 576: | Line 814: | ||
| _ -> yorn() |
| _ -> yorn() |
||
printfn "\nYour choice: %c" (yorn())</ |
printfn "\nYour choice: %c" (yorn())</syntaxhighlight> |
||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
< |
<syntaxhighlight lang="forth">: flush ( -- ) \ discard pending input |
||
begin key? while key drop repeat ; |
begin key? while key drop repeat ; |
||
Line 608: | Line 846: | ||
[char] n of 2drop false exit endof |
[char] n of 2drop false exit endof |
||
[char] N of 2drop false exit endof |
[char] N of 2drop false exit endof |
||
endcase again ;</ |
endcase again ;</syntaxhighlight> |
||
=={{header|Fortran}}== |
=={{header|Fortran}}== |
||
Line 614: | Line 852: | ||
Even so, asking questions can often be useful when messing about with tests, etc., so some routines for this can help. These were devised afresh at the Culham Science Centre, so there was some language generality: |
Even so, asking questions can often be useful when messing about with tests, etc., so some routines for this can help. These were devised afresh at the Culham Science Centre, so there was some language generality: |
||
<syntaxhighlight lang="fortran"> |
|||
<lang Fortran> |
|||
CHARACTER*120 FUNCTION REPLY(QUERY) !Obtain a text in reply. |
CHARACTER*120 FUNCTION REPLY(QUERY) !Obtain a text in reply. |
||
Concocted by R.N.McLean (whom God preserve), December MM. |
Concocted by R.N.McLean (whom God preserve), December MM. |
||
Line 678: | Line 916: | ||
RETURN !Pass the inverted word. |
RETURN !Pass the inverted word. |
||
END !So much for naysayers. |
END !So much for naysayers. |
||
</syntaxhighlight> |
|||
</lang> |
|||
Usage might be something like <code>IF (NAY("Keep the results")) CALL PURGE</code> |
Usage might be something like <code>IF (NAY("Keep the results")) CALL PURGE</code> |
||
=={{header|FreeBASIC}}== |
=={{header|FreeBASIC}}== |
||
< |
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
||
While InKey <> "" : Wend '' flush keyboard buffer |
While InKey <> "" : Wend '' flush keyboard buffer |
||
Line 699: | Line 937: | ||
End If |
End If |
||
Sleep</ |
Sleep</syntaxhighlight> |
||
Sample input/output: |
Sample input/output: |
||
Line 710: | Line 948: | ||
=={{header|FutureBasic}}== |
=={{header|FutureBasic}}== |
||
<syntaxhighlight lang="futurebasic">void local fn DoDialog( ev as long ) |
|||
<lang futurebasic> |
|||
CFStringRef key |
|||
local fn DoDialog |
|||
dim as long ev, id |
|||
select ( ev ) |
|||
case _windowKeyDown |
|||
ev = dialog(0) |
|||
cls |
|||
id = dialog(ev) |
|||
key = fn EventCharacters |
|||
select |
select ( lcase(key) ) |
||
case @"y",@"n" |
|||
case _wndClose : end |
|||
printf @"You pressed the \"%@\" key",key |
|||
case _evKey |
|||
DialogEventSetBool(YES)// we handled the event |
|||
select id |
|||
end select |
|||
// Trap upper and lower case Y and N |
|||
case 78, 110 : cls : print "No " |
|||
case 89, 121 : cls : print "Yes" |
|||
end select |
|||
end select |
end select |
||
end fn |
end fn |
||
subclass |
|||
window 1, @"Press \"Y\" or \"N\" keys", (0,0,550,400) |
|||
on dialog fn DoDialog |
on dialog fn DoDialog |
||
HandleEvents</syntaxhighlight> |
|||
window 1, @"Yes-No", (0,0)-(150,80), _docNoGrow |
|||
text _applFont, 14, _boldBit% |
|||
RunApplicationEventLoop() |
|||
</lang> |
|||
=={{header|GlovePIE}}== |
=={{header|GlovePIE}}== |
||
< |
<syntaxhighlight lang="glovepie">if var.end=0 then |
||
var.end=0 |
var.end=0 |
||
debug="Press the Y key or the N key to continue:" |
debug="Press the Y key or the N key to continue:" |
||
Line 748: | Line 982: | ||
var.end=1 |
var.end=1 |
||
debug="You pressed the N key." |
debug="You pressed the N key." |
||
endif</ |
endif</syntaxhighlight> |
||
=={{header|Go}}== |
=={{header|Go}}== |
||
{{libheader|Curses}} |
{{libheader|Curses}} |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 781: | Line 1,015: | ||
s.Refresh() |
s.Refresh() |
||
s.GetChar() |
s.GetChar() |
||
}</ |
}</syntaxhighlight> |
||
::< |
::<syntaxhighlight lang="go">package main |
||
// siongui.github.io/2016/04/23/go-read-yes-no-from-console |
// siongui.github.io/2016/04/23/go-read-yes-no-from-console |
||
import ( |
import ( |
||
Line 808: | Line 1,042: | ||
fmt.Println("no") |
fmt.Println("no") |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|GW-BASIC}}== |
=={{header|GW-BASIC}}== |
||
< |
<syntaxhighlight lang="qbasic">10 IF INKEY$<>"" THEN GOTO 10: REM flush the keyboard buffer |
||
20 PRINT "Press Y or N to continue" |
20 PRINT "Press Y or N to continue" |
||
30 LET k$ = INKEY$ |
30 LET k$ = INKEY$ |
||
40 IF k$ <> "y" AND k$ <> "Y" AND k$ <> "n" AND k$ <> "N" THEN GOTO 30 |
40 IF k$ <> "y" AND k$ <> "Y" AND k$ <> "n" AND k$ <> "N" THEN GOTO 30 |
||
50 PRINT "The response was "; k$</ |
50 PRINT "The response was "; k$</syntaxhighlight> |
||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
Line 821: | Line 1,055: | ||
This may not be very idiomatic; it's pretty monad-oriented, and the use of do expressions makes the whole thing feel rather imperative. |
This may not be very idiomatic; it's pretty monad-oriented, and the use of do expressions makes the whole thing feel rather imperative. |
||
< |
<syntaxhighlight lang="haskell">import System.IO |
||
hFlushInput :: Handle -> IO () |
hFlushInput :: Handle -> IO () |
||
Line 849: | Line 1,083: | ||
hFlushInput stdin |
hFlushInput stdin |
||
answer <- yorn |
answer <- yorn |
||
putStrLn [answer]</ |
putStrLn [answer]</syntaxhighlight> |
||
=={{header|Icon}} and {{header|Unicon}}== |
=={{header|Icon}} and {{header|Unicon}}== |
||
This solution works in both Icon and Unicon. It also accepts <tt>y</tt> or <tt>n</tt>. |
This solution works in both Icon and Unicon. It also accepts <tt>y</tt> or <tt>n</tt>. |
||
< |
<syntaxhighlight lang="unicon">procedure main() |
||
write("Response was ",getResponse("OK? (Y or N): ")) |
write("Response was ",getResponse("OK? (Y or N): ")) |
||
end |
end |
||
Line 863: | Line 1,097: | ||
repeat if map(answer := getch()) == ("y"|"n") then break |
repeat if map(answer := getch()) == ("y"|"n") then break |
||
return answer |
return answer |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Inform 7}}== |
=={{header|Inform 7}}== |
||
Line 870: | Line 1,104: | ||
Inform 7 has a built-in function to ask the user for yes-or-no input, but it requires them to press enter afterward: |
Inform 7 has a built-in function to ask the user for yes-or-no input, but it requires them to press enter afterward: |
||
< |
<syntaxhighlight lang="inform7">Qwantz is a room. |
||
When play begins: |
When play begins: |
||
say "A wizard has turned you into a whale. Is this awesome (Y/N)? "; |
say "A wizard has turned you into a whale. Is this awesome (Y/N)? "; |
||
if the player consents, say "Awesome!"; |
if the player consents, say "Awesome!"; |
||
end the story.</ |
end the story.</syntaxhighlight> |
||
To read a single key without waiting for enter, we can redefine the function by including a snippet of Inform 6 code: |
To read a single key without waiting for enter, we can redefine the function by including a snippet of Inform 6 code: |
||
< |
<syntaxhighlight lang="inform7">To decide whether player consents: (- (YesOrNoKey()) -). |
||
Include (- |
Include (- |
||
Line 884: | Line 1,118: | ||
do { ch = VM_KeyChar(); } until (ch == 'y' or 'Y' or 'n' or 'N'); |
do { ch = VM_KeyChar(); } until (ch == 'y' or 'Y' or 'n' or 'N'); |
||
return ch == 'y' or 'Y'; |
return ch == 'y' or 'Y'; |
||
]; -).</ |
]; -).</syntaxhighlight> |
||
=={{header|Java}}== |
|||
The task specification that there should be no need for the user to press the enter key, |
|||
creates an awkward situation for the Java language. |
|||
However, a short program that waits for the user to press return can easily be constructed. |
|||
<syntaxhighlight lang="java"> |
|||
import java.awt.event.KeyEvent; |
|||
import java.io.IOException; |
|||
import java.awt.EventQueue; |
|||
import java.awt.event.KeyAdapter; |
|||
import javax.swing.JFrame; |
|||
public final class KeyboardInputObtainYOrN { |
|||
public static void main(String[] aArgs) { |
|||
EventQueue.invokeLater( () -> { new Test("Obtain Y or N"); } ); |
|||
} |
|||
} |
|||
final class Test extends JFrame { |
|||
public Test(String aTitle) { |
|||
super(aTitle); |
|||
addKeyListener( new YesOrNoKeyAdapter() ); |
|||
setVisible(true); |
|||
try { |
|||
while ( System.in.available() > 0 ) { |
|||
System.in.read(); |
|||
} |
|||
} catch (IOException ioe) { |
|||
ioe.printStackTrace(); |
|||
} |
|||
System.out.println("Do you want to quit the program? Y / N"); |
|||
} |
|||
} |
|||
final class YesOrNoKeyAdapter extends KeyAdapter { |
|||
@Override |
|||
public void keyPressed(KeyEvent aKeyEvent) { |
|||
if ( aKeyEvent.getKeyCode() == KeyEvent.VK_Y ) { |
|||
System.out.println("Y was pressed, quitting the program"); |
|||
Runtime.getRuntime().exit(0); |
|||
} else if ( aKeyEvent.getKeyCode() == KeyEvent.VK_N ) { |
|||
System.out.println("N was pressed, but the program is about to end anyway"); |
|||
Runtime.getRuntime().exit(0); |
|||
} else { |
|||
System.out.println("Please try again, only Y or N are acceptable"); |
|||
} |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|JavaScript}}== |
=={{header|JavaScript}}== |
||
Line 890: | Line 1,182: | ||
Here's a synchronous ES6 implementation. The synchronous code must be executed in an async function definition. In this example, `wait_key` returns the key pressed and `done` must be called decouple the listening to stdin and end the process. The example pauses for a second to show that the keys pressed before `wait_key` is called are not heard. |
Here's a synchronous ES6 implementation. The synchronous code must be executed in an async function definition. In this example, `wait_key` returns the key pressed and `done` must be called decouple the listening to stdin and end the process. The example pauses for a second to show that the keys pressed before `wait_key` is called are not heard. |
||
< |
<syntaxhighlight lang="javascript">const readline = require('readline'); |
||
readline.emitKeypressEvents(process.stdin); |
readline.emitKeypressEvents(process.stdin); |
||
process.stdin.setRawMode(true); |
process.stdin.setRawMode(true); |
||
Line 919: | Line 1,211: | ||
go(); |
go(); |
||
</syntaxhighlight> |
|||
</lang> |
|||
Here's how you can asynchronously read a single character in Node.js, using the <code>keypress</code> package. |
Here's how you can asynchronously read a single character in Node.js, using the <code>keypress</code> package. |
||
This does not seem to be possible to do synchronously in Node.js or at all in the SpiderMonkey shell. |
This does not seem to be possible to do synchronously in Node.js or at all in the SpiderMonkey shell. |
||
< |
<syntaxhighlight lang="javascript">var keypress = require('keypress'); |
||
keypress(process.stdin); |
keypress(process.stdin); |
||
Line 935: | Line 1,227: | ||
process.stdin.setRawMode(true); |
process.stdin.setRawMode(true); |
||
process.stdin.resume();</ |
process.stdin.resume();</syntaxhighlight> |
||
Using DOM events. |
Using DOM events. |
||
< |
<syntaxhighlight lang="javascript">document.body.addEventListener('keyup', function (e) { |
||
var key = String.fromCharCode(e.keyCode).toLowerCase(); |
var key = String.fromCharCode(e.keyCode).toLowerCase(); |
||
if (key === 'y' || key === 'n') { |
if (key === 'y' || key === 'n') { |
||
console.log('response is: ' + key); |
console.log('response is: ' + key); |
||
} |
} |
||
}, false);</ |
}, false);</syntaxhighlight> |
||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
Uses the Gtk library. |
Uses the Gtk library. |
||
< |
<syntaxhighlight lang="julia">using Gtk.ShortNames |
||
function keypresswindow() |
function keypresswindow() |
||
Line 972: | Line 1,264: | ||
keypresswindow() |
keypresswindow() |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Kotlin}}== |
=={{header|Kotlin}}== |
||
< |
<syntaxhighlight lang="scala">// version 1.0.6 |
||
import java.awt.event.KeyAdapter |
import java.awt.event.KeyAdapter |
||
Line 1,014: | Line 1,306: | ||
f.isVisible = true |
f.isVisible = true |
||
} |
} |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Liberty BASIC}}== |
=={{header|Liberty BASIC}}== |
||
<syntaxhighlight lang="lb"> |
|||
<lang lb> |
|||
nomainwin |
nomainwin |
||
open "Y/N" for graphics_nsb_nf as #1 |
open "Y/N" for graphics_nsb_nf as #1 |
||
Line 1,043: | Line 1,335: | ||
end |
end |
||
end sub |
end sub |
||
</ |
</syntaxhighlight> |
||
=={{header|LiveCode}}== |
=={{header|LiveCode}}== |
||
Line 1,049: | Line 1,341: | ||
In the text field, put the following in its code |
In the text field, put the following in its code |
||
< |
<syntaxhighlight lang="livecode">on KeyDown k |
||
if toUpper(k) is among the items of "Y,N" then |
if toUpper(k) is among the items of "Y,N" then |
||
answer "Thanks for your response" |
answer "Thanks for your response" |
||
Line 1,056: | Line 1,348: | ||
end if |
end if |
||
put empty into me |
put empty into me |
||
end KeyDown</ |
end KeyDown</syntaxhighlight> |
||
n.b. This sort of confirmation in GUI apps is usually presented as a dialog box with Yes/No buttons, which automatically handles keyboard input. |
n.b. This sort of confirmation in GUI apps is usually presented as a dialog box with Yes/No buttons, which automatically handles keyboard input. |
||
=={{header|Logo}}== |
=={{header|Logo}}== |
||
< |
<syntaxhighlight lang="logo">to yorn |
||
type [Press Y or N to continue: ] |
type [Press Y or N to continue: ] |
||
local "clear |
local "clear |
||
Line 1,069: | Line 1,361: | ||
print :yorn |
print :yorn |
||
output :yorn |
output :yorn |
||
end</ |
end</syntaxhighlight> |
||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
===Simple Loop using Key$=== |
===Simple Loop using Key$=== |
||
If keyboard is Greek the we have to change to English. Other examples use Keyboard codes. |
If keyboard is Greek the we have to change to English. Other examples use Keyboard codes. |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Simple { |
Module Simple { |
||
\\ a small modification from BBC BASIC entry |
\\ a small modification from BBC BASIC entry |
||
Line 1,085: | Line 1,377: | ||
} |
} |
||
Simple |
Simple |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Use a Function to return keypress and by reference return value=== |
===Use a Function to return keypress and by reference return value=== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module Checkit { |
Module Checkit { |
||
Function GetYN$ (&Ret) { |
Function GetYN$ (&Ret) { |
||
Line 1,109: | Line 1,401: | ||
} |
} |
||
Checkit |
Checkit |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Using Thread to read/write Keyboard buffer=== |
===Using Thread to read/write Keyboard buffer=== |
||
Line 1,118: | Line 1,410: | ||
Using Profiler and Print Timecount we get the real duration (using high resolution timer), of response. |
Using Profiler and Print Timecount we get the real duration (using high resolution timer), of response. |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module CheckisToo { |
Module CheckisToo { |
||
Module GetYN (&Ret) { |
Module GetYN (&Ret) { |
||
Line 1,151: | Line 1,443: | ||
} |
} |
||
CheckisToo |
CheckisToo |
||
</syntaxhighlight> |
|||
</lang> |
|||
===Using User Form (GUI)=== |
===Using User Form (GUI)=== |
||
<syntaxhighlight lang="m2000 interpreter"> |
|||
<lang M2000 Interpreter> |
|||
Module UseUIForm { |
Module UseUIForm { |
||
Const Y=0x59, N=0x4E, Center=2 |
Const Y=0x59, N=0x4E, Center=2 |
||
Line 1,175: | Line 1,467: | ||
} |
} |
||
UseUIForm |
UseUIForm |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Mathematica}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">CreateDialog[TextCell["Yes or no?[Y/N]"], |
||
NotebookEventActions -> { |
NotebookEventActions -> { |
||
"KeyDown" :> Switch[ToUpperCase@CurrentValue["EventKey"], |
"KeyDown" :> Switch[ToUpperCase@CurrentValue["EventKey"], |
||
"Y", Print["You said yes"]; DialogReturn[], |
"Y", Print["You said yes"]; DialogReturn[], |
||
"N", Print["You said no"]; DialogReturn[] |
"N", Print["You said no"]; DialogReturn[] |
||
]}];</ |
]}];</syntaxhighlight> |
||
=={{header|Microsoft Small Basic}}== |
=={{header|Microsoft Small Basic}}== |
||
Line 1,189: | Line 1,481: | ||
Submitted by: '''AykayayCiti''' (''Earl L. Montgomery'') on Mar 19, 2018. |
Submitted by: '''AykayayCiti''' (''Earl L. Montgomery'') on Mar 19, 2018. |
||
Once you hit a key a separate dialog box will appear. Place them side by side to see the results. |
Once you hit a key a separate dialog box will appear. Place them side by side to see the results. |
||
< |
<syntaxhighlight lang="vb">'From: |
||
'Andy Oneill, 2-6-2015, "Small Basic: Key Input, |
'Andy Oneill, 2-6-2015, "Small Basic: Key Input, |
||
'" TechNet, https://social.technet.microsoft.com/wiki/contents/articles/29850.small-basic-key-input.aspx, accessed 3-19-2018 |
'" TechNet, https://social.technet.microsoft.com/wiki/contents/articles/29850.small-basic-key-input.aspx, accessed 3-19-2018 |
||
Line 1,197: | Line 1,489: | ||
Sub OnKeyDown |
Sub OnKeyDown |
||
TextWindow.WriteLine(GraphicsWindow.LastKey) |
TextWindow.WriteLine(GraphicsWindow.LastKey) |
||
EndSub</ |
EndSub</syntaxhighlight> |
||
=={{header|MiniScript}}== |
=={{header|MiniScript}}== |
||
Line 1,203: | Line 1,495: | ||
Access to hardware like the keyboard is very dependent on the host app, but here's a version that works with [https://miniscript.org/MiniMicro/ MiniMicro], a standardized MiniScript virtual machine. |
Access to hardware like the keyboard is very dependent on the host app, but here's a version that works with [https://miniscript.org/MiniMicro/ MiniMicro], a standardized MiniScript virtual machine. |
||
< |
<syntaxhighlight lang="miniscript">// flush the keyboard |
||
while key.available |
while key.available |
||
key.get |
key.get |
||
Line 1,214: | Line 1,506: | ||
k = key.get.upper |
k = key.get.upper |
||
end while |
end while |
||
print "You pressed: " + k</ |
print "You pressed: " + k</syntaxhighlight> |
||
=={{header|MUMPS}}== |
=={{header|MUMPS}}== |
||
{{works with|Caché ObjectScript}} |
{{works with|Caché ObjectScript}} |
||
Version from terminal shown below. |
Version from terminal shown below. |
||
< |
<syntaxhighlight lang="mumps">for read !,"Enter Y or N to continue: ",input quit:input?1(1"Y",1"y",1"N",1"n")</syntaxhighlight> |
||
{{out}}<pre>Enter Y or N to continue: J |
{{out}}<pre>Enter Y or N to continue: J |
||
Line 1,228: | Line 1,520: | ||
=={{header|NetRexx}}== |
=={{header|NetRexx}}== |
||
< |
<syntaxhighlight lang="netrexx">/* NetRexx */ |
||
options replace format comments java crossref savelog symbols binary |
options replace format comments java crossref savelog symbols binary |
||
Line 1,238: | Line 1,530: | ||
when c='N' Then Say 'NO' |
when c='N' Then Say 'NO' |
||
otherwise Say 'Undecided' |
otherwise Say 'Undecided' |
||
End </ |
End </syntaxhighlight> |
||
=={{header|Nim}}== |
|||
{{libheader|gintro}} |
|||
Using "gintro" bindings to Gtk3. |
|||
<syntaxhighlight lang="nim">import strformat |
|||
import gintro/[glib, gobject, gtk, gio] |
|||
import gintro/gdk except Window |
|||
#--------------------------------------------------------------------------------------------------- |
|||
proc onKeyPress(window: ApplicationWindow; event: Event; label: Label): bool = |
|||
var keyval: int |
|||
if not event.getKeyval(keyval): return false |
|||
if keyval in [ord('n'), ord('y')]: |
|||
label.setText(&"You pressed key '{chr(keyval)}'") |
|||
result = true |
|||
#--------------------------------------------------------------------------------------------------- |
|||
proc activate(app: Application) = |
|||
## Activate the application. |
|||
let window = app.newApplicationWindow() |
|||
window.setTitle("Y/N response") |
|||
let hbox = newBox(Orientation.horizontal, 0) |
|||
window.add(hbox) |
|||
let vbox = newBox(Orientation.vertical, 10) |
|||
hbox.packStart(vbox, true, true, 20) |
|||
let label1 = newLabel(" Press 'y' or 'n' key ") |
|||
vbox.packStart(label1, true, true, 5) |
|||
let label2 = newLabel() |
|||
vbox.packStart(label2, true, true, 5) |
|||
discard window.connect("key-press-event", onKeyPress, label2) |
|||
window.showAll() |
|||
#——————————————————————————————————————————————————————————————————————————————————————————————————— |
|||
let app = newApplication(Application, "Rosetta.YNResponse") |
|||
discard app.connect("activate", activate) |
|||
discard app.run()</syntaxhighlight> |
|||
=={{header|NS-HUBASIC}}== |
=={{header|NS-HUBASIC}}== |
||
< |
<syntaxhighlight lang="ns-hubasic">10 PRINT "PRESS Y OR N TO CONTINUE." |
||
20 IF INKEY$<>"Y" AND INKEY$<>"N" THEN GOTO 20 |
20 IF INKEY$<>"Y" AND INKEY$<>"N" THEN GOTO 20 |
||
30 PRINT "THE RESPONSE WAS ";INKEY$;"."</ |
30 PRINT "THE RESPONSE WAS ";INKEY$;"."</syntaxhighlight> |
||
=={{header|OCaml}}== |
|||
<code>Unix</code> module, exposing POSIX interfaces like [https://en.wikipedia.org/wiki/POSIX_terminal_interface termios], is normally bundled with any standard OCaml distribution. Utilizing termios is the solution many other language examples here went with. |
|||
OCaml needs to link to the bundled unix archives correctly in order to compile / run code that uses definitions within the module. To do this with the plain OCaml toolchain, remember to add the library archive to the commandline like so: |
|||
<code>ocaml unix.cma <yourfile.ml></code> interpreted<br/> |
|||
<code>ocamlc -o <progname> unix.cma <yourfile.ml></code> bytecode executable<br/> |
|||
<code>ocamlopt -o <progname> unix.cmxa <yourfile.ml></code> native executable |
|||
Here we define some helper functions that we'll use: |
|||
<syntaxhighlight lang="ocaml">let attrs = Unix.(tcgetattr stdin) |
|||
let buf = Bytes.create 1 |
|||
let prompt switch = |
|||
Unix.(tcsetattr stdin TCSAFLUSH) |
|||
@@ if switch then { attrs with c_icanon = false } else attrs |
|||
let getchar () = |
|||
let len = Unix.(read stdin) buf 0 1 in |
|||
if len = 0 then raise End_of_file else Bytes.get buf 0</syntaxhighlight> |
|||
Now the main program: |
|||
<syntaxhighlight lang="ocaml">let rec loop () = |
|||
print_string "Prompt? [Y/N]: "; flush stdout; |
|||
loop |
|||
@@ print_endline |
|||
@@ match getchar () with |
|||
| 'n' | 'N' -> raise Exit |
|||
| 'y' | 'Y' -> ": Ok." |
|||
| _ -> ": Invalid." |
|||
let _ = try loop @@ prompt true with Exit | End_of_file -> prompt false</syntaxhighlight> |
|||
=={{header|Oforth}}== |
=={{header|Oforth}}== |
||
< |
<syntaxhighlight lang="oforth">import: console |
||
: YorN |
: YorN |
||
Line 1,256: | Line 1,627: | ||
c 'Y' <> c 'N' <> and |
c 'Y' <> c 'N' <> and |
||
] |
] |
||
c ;</ |
c ;</syntaxhighlight> |
||
=={{header|OpenEdge/Progress}}== |
=={{header|OpenEdge/Progress}}== |
||
< |
<syntaxhighlight lang="progress">DEF VAR lanswer AS LOGICAL INITIAL ?. |
||
DO WHILE lanswer = ?: |
DO WHILE lanswer = ?: |
||
Line 1,267: | Line 1,638: | ||
END. |
END. |
||
MESSAGE lanswer VIEW-AS ALERT-BOX.</ |
MESSAGE lanswer VIEW-AS ALERT-BOX.</syntaxhighlight> |
||
=={{header|PARI/GP}}== |
=={{header|PARI/GP}}== |
||
Line 1,276: | Line 1,647: | ||
{{works with|Free_Pascal}} |
{{works with|Free_Pascal}} |
||
{{libheader|CRT}} |
{{libheader|CRT}} |
||
< |
<syntaxhighlight lang="pascal">Program ObtainYN; |
||
uses |
uses |
||
Line 1,291: | Line 1,662: | ||
writeln; |
writeln; |
||
writeln ('Your answer was: ', key); |
writeln ('Your answer was: ', key); |
||
end.</ |
end.</syntaxhighlight> |
||
Output: |
Output: |
||
<pre>% ./ObtainYN |
<pre>% ./ObtainYN |
||
Line 1,299: | Line 1,670: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">use Term::ReadKey; |
||
ReadMode 4; # change to raw input mode |
ReadMode 4; # change to raw input mode |
||
Line 1,315: | Line 1,686: | ||
print "\nYou typed: $key\n"; |
print "\nYou typed: $key\n"; |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
{{libheader|Phix/basics}} |
|||
<lang Phix>integer key |
|||
For 1970s-style character console (/beginner) applications: |
|||
<!--<syntaxhighlight lang="phix">--> |
|||
while get_key()!=-1 do end while -- flush |
|||
<span style="color: #004080;">integer</span> <span style="color: #000000;">key</span> |
|||
puts(1,"Your answer? (Y/N)") |
|||
<span style="color: #008080;">while</span> <span style="color: #7060A8;">get_key</span><span style="color: #0000FF;">()!=-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span> <span style="color: #008080;">end</span> <span style="color: #008080;">while</span> <span style="color: #000080;font-style:italic;">-- flush</span> |
|||
while 1 do |
|||
key = upper(get_key()) |
|||
if find(key,"YN") then exit end if |
|||
end while |
|||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Your answer? (Y/N)"</span><span style="color: #0000FF;">)</span> |
|||
printf(1,"\nYour response was %s\n",key)</lang> |
|||
<span style="color: #008080;">while</span> <span style="color: #000000;">1</span> <span style="color: #008080;">do</span> |
|||
<span style="color: #000000;">key</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">upper</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_key</span><span style="color: #0000FF;">())</span> |
|||
<span style="color: #008080;">if</span> <span style="color: #7060A8;">find</span><span style="color: #0000FF;">(</span><span style="color: #000000;">key</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"YN"</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span> |
|||
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\nYour response was %s\n"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">key</span><span style="color: #0000FF;">)</span> |
|||
<!--</syntaxhighlight>--> |
|||
For GUI (graphical user interface) applications, use something more like this: |
|||
<!--<syntaxhighlight lang="phix">--> |
|||
<span style="color: #008080;">function</span> <span style="color: #000000;">key_cb</span><span style="color: #0000FF;">(</span><span style="color: #004080;">Ihandle</span> <span style="color: #000080;font-style:italic;">/*ih*/</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">atom</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #008080;">if</span> <span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)=</span><span style="color: #008000;">'y'</span> <span style="color: #008080;">then</span> <span style="color: #000000;">y_keyed</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
<span style="color: #008080;">if</span> <span style="color: #7060A8;">lower</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)=</span><span style="color: #008000;">'n'</span> <span style="color: #008080;">then</span> <span style="color: #000000;">n_keyed</span><span style="color: #0000FF;">()</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span> |
|||
<span style="color: #008080;">return</span> <span style="color: #004600;">IUP_CONTINUE</span> |
|||
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span> |
|||
<span style="color: #7060A8;">IupSetCallback</span><span style="color: #0000FF;">(</span><span style="color: #000000;">dlg</span><span style="color: #0000FF;">,</span> <span style="color: #008000;">"K_ANY"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">Icallback</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"key_cb"</span><span style="color: #0000FF;">))</span> |
|||
<!--</syntaxhighlight>--> |
|||
See [[Keyboard_macros#Phix]] or [[Conway%27s_Game_of_Life#Phix]] for a more complete example |
|||
=={{header|PicoLisp}}== |
=={{header|PicoLisp}}== |
||
< |
<syntaxhighlight lang="picolisp">(de yesno () |
||
(loop |
(loop |
||
(NIL (uppc (key))) |
(NIL (uppc (key))) |
||
(T (= "Y" @) T) |
(T (= "Y" @) T) |
||
(T (= "N" @)) ) )</ |
(T (= "N" @)) ) )</syntaxhighlight> |
||
=={{header|PL/I}}== |
=={{header|PL/I}}== |
||
< |
<syntaxhighlight lang="pli"> yn: Proc Options(main): |
||
Dcl sysin stream input; |
Dcl sysin stream input; |
||
Dcl sysprint stream output; |
Dcl sysprint stream output; |
||
Line 1,353: | Line 1,739: | ||
Put Skip List('Undecided?'); |
Put Skip List('Undecided?'); |
||
End; |
End; |
||
End;</ |
End;</syntaxhighlight> |
||
=={{header|PowerShell}}== |
=={{header|PowerShell}}== |
||
This is for console use only. The ISE is geared for a different type of input. |
This is for console use only. The ISE is geared for a different type of input. |
||
<syntaxhighlight lang="powershell"> |
|||
<lang PowerShell> |
|||
do |
do |
||
{ |
{ |
||
Line 1,365: | Line 1,751: | ||
$keyPress | Format-Table -AutoSize |
$keyPress | Format-Table -AutoSize |
||
</syntaxhighlight> |
|||
</lang> |
|||
If the user pressed the "Y" key... |
If the user pressed the "Y" key... |
||
{{Out}} |
{{Out}} |
||
Line 1,383: | Line 1,769: | ||
=={{header|PureBasic}}== |
=={{header|PureBasic}}== |
||
Inkey() returns the character string of the key which is being pressed at the time. |
Inkey() returns the character string of the key which is being pressed at the time. |
||
< |
<syntaxhighlight lang="purebasic">PrintN("Press Y or N to continue") |
||
Repeat |
Repeat |
||
Line 1,394: | Line 1,780: | ||
Delay(1) |
Delay(1) |
||
Until Key$="Y" Or Key$="N" |
Until Key$="Y" Or Key$="N" |
||
PrintN("The response was "+Key$)</ |
PrintN("The response was "+Key$)</syntaxhighlight> |
||
=={{header|Python}}== |
=={{header|Python}}== |
||
< |
<syntaxhighlight lang="python">#!/usr/bin/env python |
||
try: |
try: |
||
Line 1,418: | Line 1,804: | ||
if char.lower() in ("y", "n"): |
if char.lower() in ("y", "n"): |
||
print char |
print char |
||
break</ |
break</syntaxhighlight> |
||
---- |
---- |
||
< |
<syntaxhighlight lang="python">#!/usr/bin/env python |
||
# -*- coding: utf-8 -*- |
# -*- coding: utf-8 -*- |
||
from curses import wrapper |
from curses import wrapper |
||
Line 1,447: | Line 1,833: | ||
if __name__ == "__main__": |
if __name__ == "__main__": |
||
# |
# |
||
wrapper(main)</ |
wrapper(main)</syntaxhighlight> |
||
=={{header|QB64}}== |
=={{header|QB64}}== |
||
''CBTJD'': 2020/03/15 |
''CBTJD'': 2020/03/15 |
||
< |
<syntaxhighlight lang="qbasic">WHILE INKEY$ <> "": WEND ' Flushes keyboard buffer. |
||
PRINT "Do you want to continue? (Y/N)" |
PRINT "Do you want to continue? (Y/N)" |
||
DO |
DO |
||
k$ = UCASE$(INKEY$) ' Forces key response to upper case. |
k$ = UCASE$(INKEY$) ' Forces key response to upper case. |
||
LOOP UNTIL k$ = "Y" OR k$ = "N" |
LOOP UNTIL k$ = "Y" OR k$ = "N" |
||
PRINT "You pressed " + CHR$(34) + k$ + CHR$(34) + "." ' CHR$(34) prints quotation marks.</ |
PRINT "You pressed " + CHR$(34) + k$ + CHR$(34) + "." ' CHR$(34) prints quotation marks.</syntaxhighlight> |
||
=={{header|QUACKASM}}== |
=={{header|QUACKASM}}== |
||
Note: The following is not a full program (it is only a subroutine, using standard calling conventions), nor does it flush the keyboard buffer (there is no standard way to do this in QUACKVM; it may be possible using extensions, but none are currently defined). |
Note: The following is not a full program (it is only a subroutine, using standard calling conventions), nor does it flush the keyboard buffer (there is no standard way to do this in QUACKVM; it may be possible using extensions, but none are currently defined). |
||
< |
<syntaxhighlight lang="quackasm"> |
||
; Stores result in cell 2; 1 if yes, 0 if no. |
; Stores result in cell 2; 1 if yes, 0 if no. |
||
:YORN |
:YORN |
||
Line 1,474: | Line 1,860: | ||
RETURN |
RETURN |
||
:YORNMSG " (Y/N)? \ |
:YORNMSG " (Y/N)? \ |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Racket}}== |
=={{header|Racket}}== |
||
<syntaxhighlight lang="racket"> |
|||
<lang Racket> |
|||
#lang racket |
#lang racket |
||
Line 1,498: | Line 1,884: | ||
[else (loop)])) |
[else (loop)])) |
||
(stty tty-settings) |
(stty tty-settings) |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
(formerly Perl 6) |
(formerly Perl 6) |
||
<lang |
<syntaxhighlight lang="raku" line>my $TTY = open("/dev/tty"); |
||
sub prompt-char($prompt) { |
sub prompt-char($prompt) { |
||
Line 1,512: | Line 1,898: | ||
} |
} |
||
say so prompt-char("Y or N? ") ~~ /:i y/;</ |
say so prompt-char("Y or N? ") ~~ /:i y/;</syntaxhighlight> |
||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
Line 1,528: | Line 1,914: | ||
<br>Some older Classic REXX interpreters have a keyboard read subroutine (BIF) so that the program can read keyboard keys as |
<br>Some older Classic REXX interpreters have a keyboard read subroutine (BIF) so that the program can read keyboard keys as |
||
<br>they are pressed (see the other versions below). |
<br>they are pressed (see the other versions below). |
||
< |
<syntaxhighlight lang="rexx">/*REXX program tests for a Y or N key when entered from keyboard after a prompt.*/ |
||
do queued(); pull; end /*flush the stack if anything is queued*/ |
do queued(); pull; end /*flush the stack if anything is queued*/ |
||
Line 1,539: | Line 1,925: | ||
ans=space(ans, 0) /*elide all blanks. */ |
ans=space(ans, 0) /*elide all blanks. */ |
||
end /*until*/ |
end /*until*/ |
||
/*stick a fork in it, we're all done. */</ |
/*stick a fork in it, we're all done. */</syntaxhighlight> |
||
===version 1 for PC/REXX and Personal REXX=== |
===version 1 for PC/REXX and Personal REXX=== |
||
This version of a REXX program works with PC/REXX and Personal REXX. |
This version of a REXX program works with PC/REXX and Personal REXX. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program tests for a Y or N key when entered from keyboard after a prompt.*/ |
||
prompt = 'Please enter Y or N for verification:' /*this is the PROMPT message.*/ |
prompt = 'Please enter Y or N for verification:' /*this is the PROMPT message.*/ |
||
Line 1,550: | Line 1,936: | ||
ans=inKey('wait') /*get the answer(s) from the terminal. */ |
ans=inKey('wait') /*get the answer(s) from the terminal. */ |
||
end /*until*/ |
end /*until*/ |
||
/*stick a fork in it, we're all done. */</ |
/*stick a fork in it, we're all done. */</syntaxhighlight> |
||
===version 2 for PC/REXX and Personal REXX=== |
===version 2 for PC/REXX and Personal REXX=== |
||
This version is the same as above, but has a more idiomatic technique for testing the response. |
This version is the same as above, but has a more idiomatic technique for testing the response. |
||
< |
<syntaxhighlight lang="rexx">/*REXX program tests for a Y or N key when entered from keyboard after a prompt.*/ |
||
prompt = 'Please enter Y or N for verification:' /*this is the PROMPT message.*/ |
prompt = 'Please enter Y or N for verification:' /*this is the PROMPT message.*/ |
||
Line 1,561: | Line 1,947: | ||
ans=inKey('wait'); upper ans /*get the answer(s); and uppercase it.*/ |
ans=inKey('wait'); upper ans /*get the answer(s); and uppercase it.*/ |
||
end /*until*/ |
end /*until*/ |
||
/*stick a fork in it, we're all done. */</ |
/*stick a fork in it, we're all done. */</syntaxhighlight> |
||
=={{header|Ring}}== |
=={{header|Ring}}== |
||
< |
<syntaxhighlight lang="ring"> |
||
while true |
while true |
||
give c |
give c |
||
Line 1,571: | Line 1,957: | ||
else see "Try again!" + nl ok |
else see "Try again!" + nl ok |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|RPL}}== |
|||
≪ "Yes or No?" 1 DISP |
|||
'''DO''' |
|||
'''DO UNTIL''' KEY '''END''' |
|||
'''UNTIL''' "YN" SWAP POS '''END''' |
|||
"YN" LAST DUP SUB CLMF |
|||
≫ |
|||
´'''TASK'''’ STO |
|||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
<syntaxhighlight lang="ruby"> |
|||
<lang Ruby> |
|||
def yesno |
def yesno |
||
begin |
begin |
||
Line 1,590: | Line 1,985: | ||
end |
end |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
Ruby provides the io/console module since version 2.0: |
Ruby provides the io/console module since version 2.0: |
||
<syntaxhighlight lang="ruby"> |
|||
<lang Ruby> |
|||
require 'io/console' |
require 'io/console' |
||
Line 1,603: | Line 1,998: | ||
end |
end |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Run BASIC}}== |
=={{header|Run BASIC}}== |
||
< |
<syntaxhighlight lang="runbasic">[loop] cls ' Clear screen |
||
html "Click Y or N" ' no other options |
html "Click Y or N" ' no other options |
||
button #y, "Y", [Y] ' they either click [Y] |
button #y, "Y", [Y] ' they either click [Y] |
||
Line 1,614: | Line 2,009: | ||
[Y] msg$ = "You entered [Y]es": goto [loop] |
[Y] msg$ = "You entered [Y]es": goto [loop] |
||
[N] msg$ = "You entered [N]o" : goto [loop] |
[N] msg$ = "You entered [N]o" : goto [loop] |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Rust}}== |
=={{header|Rust}}== |
||
{{libheader|Ncurses}} |
{{libheader|Ncurses}} |
||
< |
<syntaxhighlight lang="rust">//cargo-deps: ncurses |
||
extern crate ncurses; |
extern crate ncurses; |
||
Line 1,638: | Line 2,033: | ||
refresh(); |
refresh(); |
||
endwin(); |
endwin(); |
||
}</ |
}</syntaxhighlight> |
||
=={{header|Scala}}== |
=={{header|Scala}}== |
||
< |
<syntaxhighlight lang="scala"> println(if (scala.io.StdIn.readBoolean) "Yes typed." else "Something else.")</syntaxhighlight> |
||
---- |
---- |
||
< |
<syntaxhighlight lang="scala"> |
||
import java.io.InputStreamReader |
import java.io.InputStreamReader |
||
val in = new InputStreamReader(System.in) |
val in = new InputStreamReader(System.in) |
||
if (Seq(121, 89, 110, 78).contains(in.read()) ) {println("Yes|No")} else {println("other")} |
if (Seq(121, 89, 110, 78).contains(in.read()) ) {println("Yes|No")} else {println("other")} |
||
</syntaxhighlight> |
|||
</lang> |
|||
---- |
---- |
||
< |
<syntaxhighlight lang="scala"> |
||
import scala.io.{Source, BufferedSource} |
import scala.io.{Source, BufferedSource} |
||
val kbd_In: BufferedSource = Source.stdin |
val kbd_In: BufferedSource = Source.stdin |
||
Line 1,656: | Line 2,051: | ||
//res?: Char = 'y' not :String = "y" |
//res?: Char = 'y' not :String = "y" |
||
if (Seq('y', 'Y', 'n', 'Y').contains(kbd_In.next()) ) {println("Typed y|Y|n|N")} else {println("other key")} |
if (Seq('y', 'Y', 'n', 'Y').contains(kbd_In.next()) ) {println("Typed y|Y|n|N")} else {println("other key")} |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|Seed7}}== |
=={{header|Seed7}}== |
||
< |
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
||
include "keybd.s7i"; |
include "keybd.s7i"; |
||
Line 1,668: | Line 2,063: | ||
var char: answer is ' '; |
var char: answer is ' '; |
||
begin |
begin |
||
while |
while inputReady(KEYBOARD) do |
||
ignore(getc(KEYBOARD)); |
ignore(getc(KEYBOARD)); |
||
end while; |
end while; |
||
Line 1,681: | Line 2,076: | ||
begin |
begin |
||
writeln(yesOrNo("Press Y or N to continue ")); |
writeln(yesOrNo("Press Y or N to continue ")); |
||
end func;</ |
end func;</syntaxhighlight> |
||
=={{header|Sidef}}== |
=={{header|Sidef}}== |
||
{{trans|Perl}} |
{{trans|Perl}} |
||
< |
<syntaxhighlight lang="ruby">func prompt_yn { |
||
static rk = frequire('Term::ReadKey'); |
static rk = frequire('Term::ReadKey'); |
||
rk.ReadMode(4); # change to raw input mode |
rk.ReadMode(4); # change to raw input mode |
||
Line 1,701: | Line 2,096: | ||
var key = prompt_yn(); |
var key = prompt_yn(); |
||
say "You typed: #{key}";</ |
say "You typed: #{key}";</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 1,710: | Line 2,105: | ||
You typed: Y |
You typed: Y |
||
</pre> |
</pre> |
||
=={{header|SparForte}}== |
|||
As a structured script. |
|||
<syntaxhighlight lang="ada">#!/usr/local/bin/spar |
|||
pragma annotate( summary, "yorn" ); |
|||
pragma annotate( description, "Obtain a valid Y or N response from the keyboard. The" ); |
|||
pragma annotate( description, "keyboard should be flushed, so that any outstanding keypresses" ); |
|||
pragma annotate( description, "are removed, preventing any existing Y or N keypress from" ); |
|||
pragma annotate( description, "being evaluated. The response should be obtained as soon as" ); |
|||
pragma annotate( description, "Y or N are pressed, and there should be no need to press an" ); |
|||
pragma annotate( description, "enter key. " ); |
|||
pragma annotate( see_also, "http://rosettacode.org/wiki/Keyboard_Input/Obtain_a_Y_or_N_response" ); |
|||
pragma annotate( author, "Ken O. Burtch" ); |
|||
pragma ada_95; |
|||
pragma restriction( no_external_commands ); |
|||
procedure yorn is |
|||
answer : character; |
|||
begin |
|||
put( "Your answer? (Y/N) " ); |
|||
loop |
|||
answer := inkey; |
|||
case answer is |
|||
when 'Y'|'y' => |
|||
answer := 'Y'; |
|||
exit; |
|||
when 'N'|'n' => |
|||
answer := 'N'; |
|||
exit; |
|||
when others => |
|||
null; |
|||
end case; |
|||
end loop; |
|||
put_line( answer ); |
|||
end yorn;</syntaxhighlight> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |
||
Line 1,715: | Line 2,146: | ||
Using the console (expects U*Xish <tt>stty</tt>) |
Using the console (expects U*Xish <tt>stty</tt>) |
||
< |
<syntaxhighlight lang="tcl">proc yesno {{message "Press Y or N to continue"}} { |
||
fconfigure stdin -blocking 0 |
fconfigure stdin -blocking 0 |
||
exec stty raw |
exec stty raw |
||
Line 1,731: | Line 2,162: | ||
} |
} |
||
set yn [yesno "Do you like programming (Y/N)"]</ |
set yn [yesno "Do you like programming (Y/N)"]</syntaxhighlight> |
||
Without a console (answer in the global variable yn; this should work in any GUI for which there is a TCL): |
Without a console (answer in the global variable yn; this should work in any GUI for which there is a TCL): |
||
< |
<syntaxhighlight lang="tcl"> |
||
proc yesno {message} { |
proc yesno {message} { |
||
toplevel .msg |
toplevel .msg |
||
Line 1,748: | Line 2,179: | ||
yesno "Do you like programming?" |
yesno "Do you like programming?" |
||
</syntaxhighlight> |
|||
</lang> |
|||
=={{header|TXR}}== |
=={{header|TXR}}== |
||
Line 1,754: | Line 2,185: | ||
This works not only on Unix-like platforms, but also on Microsoft Windows, because TXR is ported to Windows using a [https://www.kylheku.com/cygnal/index.html modified version of Cygwin]. |
This works not only on Unix-like platforms, but also on Microsoft Windows, because TXR is ported to Windows using a [https://www.kylheku.com/cygnal/index.html modified version of Cygwin]. |
||
< |
<syntaxhighlight lang="txrlisp">(with-resources ((tio-orig (tcgetattr) (tcsetattr tio-orig))) |
||
(let ((tio (copy tio-orig))) |
(let ((tio (copy tio-orig))) |
||
tio.(go-raw) |
tio.(go-raw) |
||
(tcsetattr tio tcsaflush) ;; third arg optional, defaults to tcsadrain |
(tcsetattr tio tcsaflush) ;; third arg optional, defaults to tcsadrain |
||
(whilet ((k (get-char)) |
(whilet ((k (get-char)) |
||
((not (member k '(#\y #\n #\Y #\N))))))))</ |
((not (member k '(#\y #\n #\Y #\N))))))))</syntaxhighlight> |
||
The <code>go-raw</code> method on the <code>termios</code> structure only manipulates the structure contents; <code>tcsetattr</code> pushes it down to the TTY driver. |
The <code>go-raw</code> method on the <code>termios</code> structure only manipulates the structure contents; <code>tcsetattr</code> pushes it down to the TTY driver. |
||
Line 1,765: | Line 2,196: | ||
<code>go-raw</code> is defined in the TXR standard library like this: |
<code>go-raw</code> is defined in the TXR standard library like this: |
||
< |
<syntaxhighlight lang="txrlisp">(defmeth termios go-raw (tio) |
||
tio.(clear-iflags ignbrk brkint parmrk istrip inlcr igncr icrnl ixon) |
tio.(clear-iflags ignbrk brkint parmrk istrip inlcr igncr icrnl ixon) |
||
tio.(clear-oflags opost) |
tio.(clear-oflags opost) |
||
Line 1,774: | Line 2,205: | ||
tio.(set-cflags cs8) |
tio.(set-cflags cs8) |
||
(set tio.[cc vmin] 1) |
(set tio.[cc vmin] 1) |
||
(set tio.[cc vtime] 0))</ |
(set tio.[cc vtime] 0))</syntaxhighlight> |
||
=={{header|UNIX Shell}}== |
=={{header|UNIX Shell}}== |
||
{{works with|Bourne Again SHell}} |
{{works with|Bourne Again SHell}} |
||
< |
<syntaxhighlight lang="bash">getkey() { |
||
local stty="$(stty -g)" |
local stty="$(stty -g)" |
||
trap "stty $stty; trap SIGINT; return 128" SIGINT |
trap "stty $stty; trap SIGINT; return 128" SIGINT |
||
Line 1,801: | Line 2,232: | ||
[Nn]) echo >&2 N; return 1;; |
[Nn]) echo >&2 N; return 1;; |
||
esac |
esac |
||
}</ |
}</syntaxhighlight> |
||
Cleaner version using bash built-ins |
Cleaner version using bash built-ins |
||
< |
<syntaxhighlight lang="sh">#!/bin/bash |
||
yorn() { |
yorn() { |
||
Line 1,822: | Line 2,253: | ||
} |
} |
||
yorn</ |
yorn</syntaxhighlight> |
||
=={{header|VB-DOS}}== |
=={{header|VB-DOS}}== |
||
< |
<syntaxhighlight lang="vb">OPTION EXPLICIT |
||
DIM T AS INTEGER |
DIM T AS INTEGER |
||
T = MSGBOX("Click on yes or no", 4, "Option") |
T = MSGBOX("Click on yes or no", 4, "Option") |
||
Line 1,831: | Line 2,262: | ||
IF T = 6 THEN PRINT "yes"; ELSE PRINT "no"; |
IF T = 6 THEN PRINT "yes"; ELSE PRINT "no"; |
||
PRINT "." |
PRINT "." |
||
END</ |
END</syntaxhighlight> |
||
=={{header|Vedit macro language}}== |
=={{header|Vedit macro language}}== |
||
< |
<syntaxhighlight lang="vedit">Key_Purge() // flush keyboard buffer |
||
do { |
do { |
||
#1 = Get_Key("Are you sure? (Y/N): ") // prompt for a key |
#1 = Get_Key("Are you sure? (Y/N): ") // prompt for a key |
||
#1 &= 0xdf // to upper case |
#1 &= 0xdf // to upper case |
||
} while (#1 != 'Y' && #1 != 'N') </ |
} while (#1 != 'Y' && #1 != 'N') </syntaxhighlight> |
||
=={{header|V (Vlang)}}== |
|||
<syntaxhighlight lang="v (vlang)">import term.ui as tui |
|||
struct App { |
|||
mut: |
|||
tui &tui.Context = 0 |
|||
} |
|||
fn event(e &tui.Event, x voidptr) { |
|||
mut app := &App(x) |
|||
app.tui.clear() |
|||
app.tui.set_cursor_position(0, 0) |
|||
app.tui.write('V term.input event viewer (type `y`, `Y`, `n`, or `N` to exit)\n\n') |
|||
if e.typ == .key_down { |
|||
mut cap := '' |
|||
if !e.modifiers.is_empty() && e.modifiers.has(.shift) { |
|||
cap = 'capital' |
|||
} |
|||
match e.code { |
|||
.y { |
|||
app.tui.write('You typed $cap y') |
|||
} |
|||
.n { |
|||
app.tui.write('You typed $cap n') |
|||
} |
|||
else { |
|||
app.tui.write("You didn't type n or y") |
|||
} |
|||
} |
|||
} |
|||
app.tui.flush() |
|||
if e.typ == .key_down && (e.code == .y || e.code==.n) { |
|||
exit(0) |
|||
} |
|||
} |
|||
fn main() { |
|||
mut app := &App{} |
|||
app.tui = tui.init( |
|||
user_data: app |
|||
event_fn: event |
|||
window_title: 'V term.ui event viewer' |
|||
hide_cursor: true |
|||
capture_events: true |
|||
frame_rate: 60 |
|||
use_alternate_buffer: false |
|||
) |
|||
println('V term.input event viewer (type `y`, `Y`, `n`, or `N` to exit)\n\n') |
|||
app.tui.run()? |
|||
}</syntaxhighlight> |
|||
=={{header|Wee Basic}}== |
=={{header|Wee Basic}}== |
||
< |
<syntaxhighlight lang="wee basic">print 1 "Enter Y for yes, or N for no. (not case sensitive)" |
||
let loop=0 |
let loop=0 |
||
let keycode=0 |
let keycode=0 |
||
Line 1,861: | Line 2,344: | ||
wend |
wend |
||
print 1 "You entered"+response$ |
print 1 "You entered"+response$ |
||
end</ |
end</syntaxhighlight> |
||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
< |
<syntaxhighlight lang="wren">import "io" for Stdin, Stdout |
||
Stdin.isRaw = true // input is neither echoed nor buffered in this mode |
Stdin.isRaw = true // input is neither echoed nor buffered in this mode |
||
Line 1,876: | Line 2,359: | ||
System.print(yn) |
System.print(yn) |
||
Stdin.isRaw = false</ |
Stdin.isRaw = false</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 1,886: | Line 2,369: | ||
=={{header|XPL0}}== |
=={{header|XPL0}}== |
||
< |
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations |
||
loop [OpenI(1); \flush any pending keystroke |
loop [OpenI(1); \flush any pending keystroke |
||
case ChIn(1) of \get keystroke |
case ChIn(1) of \get keystroke |
||
Line 1,894: | Line 2,377: | ||
other ChOut(0, 7\bel\); |
other ChOut(0, 7\bel\); |
||
CrLf(0); |
CrLf(0); |
||
]</ |
]</syntaxhighlight> |
||
=={{header|Z80 Assembly}}== |
|||
{{works with|Amstrad CPC}} |
|||
This simple template can be <code>CALL</code>ed to wait for a Y/N response and act based on that. This particular template is limited in that the code that gets executed based on the response can't be changed at runtime (at least not without self-modifying code.) |
|||
<syntaxhighlight lang="z80">wait_for_key_input: |
|||
call &BB06 ;bios call, waits until key is pressed, returns key's ASCII code into A |
|||
and %11011111 ;converts to upper case |
|||
cp 'Y' |
|||
jp z,User_Chose_Yes |
|||
cp 'N' |
|||
jp z,User_Chose_No |
|||
jp wait_for_key_input |
|||
User_Chose_Yes: |
|||
;your code for what happens when the user types "Y" goes here |
|||
ret |
|||
User_Chose_No: |
|||
;your code for what happens when the user types "N" goes here |
|||
ret</syntaxhighlight> |
|||
{{omit from|GUISS}} |
{{omit from|GUISS}} |
||
[[Category:Keyboard |
[[Category:Keyboard input]] |
Latest revision as of 09:17, 5 July 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Obtain a valid Y or N response from the keyboard.
The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing Y or N key-press 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.
8080 Assembly
This program uses CP/M to read the keyboard.
rawio: equ 6 ; Raw console input
puts: equ 9 ; String output
bdos: equ 5 ; CP/M entry point
org 100h
jmp demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Routine: read 'Y' or 'N' from the keyboard.
;;; Output: carry flag clear if Y pressed, set if N pressed.
yesno: mvi c,rawio ; Read input from console
mvi e,-1
call bdos
ana a ; Read keys as long as a key is pressed
jnz yesno ; (wait until keyboard is clear)
yread: mvi c,rawio ; Then, wait for a key to be pressed
mvi e,-1
call bdos
ana a
jz yread
ori 32 ; Set bit 5 to make input letters lowercase
cpi 'y' ; If the key is Y,
rz ; then return (carry is clear here)
cpi 'n' ; If the key is N,
stc ; then set the carry flag and return
rz
jmp yread ; If it wasn't Y or N, get another key
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Demo code: use the routine to read Y or N, and then print
;;; 'yes' or 'no'.
demo: call yesno ; Read Y or N
mvi c,puts
lxi d,yes
jnc bdos ; If carry clear, print 'Yes'
lxi d,no
jmp bdos ; Otherwise, print 'No'
yes: db 'Yes$'
no: db 'No$'
8086 Assembly
- Assembled using UASM v2.49
.model small
.stack 1024
.data
;no data needed
.code
start:
mov ax,@code
mov ds,ax
call PRIMM
BYTE "Exit program and return to MS-DOS? (Y/N)",0
mov ax,0C00h
int 21h ;flush keyboard buffer
forever:
call waitKey
;returns ASCII code in AL
and AL,11011111b ;ignore case
cmp al,"Y"
jz ReturnToMSDOS
cmp al,"N"
jz forever
;normally this would jump somewhere else but for simplicity it will wait
;for a yes response.
jnz forever
ReturnToMSDOS:
mov ax,0C00h
int 21h ;flush keyboard buffer
mov ax,4C00h
int 21h ;end program
;-------------------------------------------------------------------
; SUBROUTINES
;-------------------------------------------------------------------
waitKey:
mov ah,01h
int 16h
jz waitKey
ret
;waits until a key is pressed.
;return:
; AL = ASCII CODE
; AH = SCAN CODE (???)
;-------------------------------------------------------------------
PrintString: ;Print null-terminated strings
;input: string address = ds:si
lodsb ;Load a letter
cmp al,0 ;Was that letter the terminator?
jz PrintString_Done ;Yes? then RET
call PrintChar ;Print to screen
jmp PrintString ;Repeat
PrintString_Done:
ret
;-------------------------------------------------------------------
PrintChar:
push ax
mov ah,0Eh
int 10h ;print AL to the screen.
pop ax
ret
;-------------------------------------------------------------------
PrintSpace:
mov al,' '
jmp PrintChar ;JMP avoids a tail call.
;ret ;"PrintChar"'s ret will do this for us.
;-------------------------------------------------------------------
NewLine:
push dx
push ax
mov ah, 02h
mov dl, 13 ;CR
int 21h
mov dl, 10 ;LF
int 21h
pop ax
pop dx
ret
;-------------------------------------------------------------------
PRIMM:
pop si
push ax
;get return address in si, this is the source offset for
;the string that will be printed.
;String must be null terminated.
call PrintString
pop ax
push si
;PrintString adjusts the return address for us, it is now
;just after the null terminator. So put it back on the stack.
ret
;-------------------------------------------------------------------
end start
8th
\ get a yes or no response from the keyboard
: yes-no
con:key $20 bor
dup 'y n:= if ;; then
dup 'n n:= if ;; then
drop yes-no ;
: no? 'n n:= if "No" else "Yes" then . ;
"Yes or no? " con:print yes-no no?
cr bye
Action!
PROC MAIN()
Byte Key=764
Printe("Press Y or N to continue")
key=255
Do
Until Key=43 or Key=35
Od
Print("You pressed ")
If Key=43 then Printe("Yes") Fi
If Key=35 then Printe("No ") Fi
RETURN
Ada
function Yes_Or_No (Prompt : String := "Your answer (Y/N): ") return Boolean is
Answer : Character;
begin
Ada.Text_IO.Put (Prompt);
loop
Ada.Text_IO.Get_Immediate (Answer);
case Answer is
when 'Y'|'y' => return True;
when 'N'|'n' => return False;
when others => null;
end case;
end loop;
end Yes_Or_No;
AutoHotkey
Loop, {
Input, Key, L1
if (Key = "n" || Key = "y")
break
}
MsgBox, % "The response was """ Key """."
ExitApp
AWK
# syntax: GAWK -f KEYBOARD_INPUT_OBTAIN_A_Y_OR_N_RESPONSE.AWK
BEGIN {
printf("you entered %s\n",prompt_user())
exit(0)
}
function prompt_user( rec) {
# AWK lacks the ability to get keyboard input without pressing the enter key.
while (1) {
printf("enter Y or N ")
getline rec <"con"
gsub(/ /,"",rec) # optional
if (rec ~ /^[nyNY]$/) {
break
}
}
return(rec)
}
- Output:
enter Y or N y you entered y
Axe
Since the TI-83/84 require a modifier key to access the letters, this example uses the 2nd key as Y and the Clear key as N.
While getKey(0)
End
While 1
If getKey(15)
Disp "N",i
Return
ElseIf getKey(54)
Disp "Y",i
Return
End
End
BASIC
Applesoft BASIC
10 LET C = PEEK (49168): REM CLEAR KEYBOARD
20 PRINT "PRESS Y OR N TO CONTINUE"
30 GET K$
40 IF K$ < > "Y" AND K$ < > "N" THEN 30
50 PRINT "THE RESPONSE WAS ";K$
BASIC256
print "Do you want to continue y/n : ";
do
KBD$ = key
until KBD$ = "89" or KBD$ = "78"
print chr(KBD$)
if KBD$ = "89" then
print "OK, continuing"
else
print "OK, finishing"
end if
QBasic
PRINT "Press Y or N to continue."
DO
KBD$ = ""
WHILE KBD$ = ""
KBD$ = UCASE$(INKEY$)
WEND
IF KBD$ <> "Y" AND KBD$ <> "N" THEN BEEP
LOOP UNTIL KBD$ = "Y" OR KBD$ = "N"
PRINT "The response was "; KBD$
BBC BASIC
REPEAT UNTIL INKEY$(0) = ""
PRINT "Press Y or N to continue"
REPEAT
key$ = GET$
UNTIL key$="Y" OR key$="N"
PRINT "The response was " key$
Commodore BASIC
10 PRINT "PRESS Y OR N TO CONTINUE:";
20 POKE 198, 0: REM CLEAR KEY BUFFER
30 GET K$
40 IF K$ <> "Y" AND K$ <> "N" THEN 30
50 PRINT K$
Note that 198 is the location of the keyboard buffer index on the VIC-20, C-64, and C-128. On the PET, the correct location is 158, while on the Plus/4 and C-16, it's 239.
The loop on lines 30 - 40 will cycle as fast as the interpreter can go, assigning K$ the empty string until the user presses a key. On versions of BASIC later than the 2.0 on the VIC and 64 (e.g. 3.5 on the C-16 and Plus/4, 7.0 on the C-128), GETKEY may be used in place of GET. GETKEY will wait for the user to press a key before continuing, so the polling is done in the BASIC interpreter's machine language code, and the BASIC loop only cycles when the user presses a key other than Y or N.
GW-BASIC
10 CLS: PRINT "Press Y or N to continue."
20 WHILE T$<>"y" AND T$<>"Y" AND T$<>"n" AND T$<>"N"
30 T$=""
40 WHILE T$=""
50 T$ = INKEY$
60 WEND
70 IF T$<>"y" AND T$<>"Y" AND T$<>"n" AND T$<>"N" THEN BEEP
80 WEND
90 PRINT "The response was "; T$
GW-BASIC variant
10 DEF FNUP$(C$)=CHR$(ASC(C$)-32*(ASC(C$)>96)*(ASC(C$)<123))
20 CLS: PRINT "Press Y or N to continue."
30 WHILE T$<>"Y" AND T$<>"N"
40 T$=FNUP$(INPUT$(1))
50 IF T$<>"Y" AND T$<>"N" THEN BEEP
60 WEND
70 PRINT "The response was: "; T$
IS-BASIC
100 GET K$ ! Flush the keyboard buffer
110 PRINT "Press Y or N to continue."
120 DO
130 LET K$=LCASE$(INKEY$)
140 LOOP UNTIL K$="y" OR K$="n"
150 PRINT "The response was ";K$
Locomotive Basic
10 CLEAR INPUT
20 PRINT "Press Y or N to continue"
30 a$=LOWER$(INKEY$)
40 IF a$="" THEN 30
50 IF a$="y" THEN PRINT "Yes":END
60 IF a$="n" THEN PRINT "No":END
70 PRINT "Try again"
80 GOTO 30
True BASIC
LIBRARY "DefLib.trc"
DECLARE DEF INKEY$
PRINT "Press Y or N to continue."
DO
LET kbd$ = ""
DO WHILE kbd$ = ""
LET kbd$ = UCASE$(INKEY$)
LOOP
IF kbd$ <> "Y" AND kbd$ <> "N" THEN SOUND 800, .25
LOOP UNTIL kbd$ = "Y" OR kbd$ = "N"
PRINT "The response was "; kbd$
END
SmallBASIC
PRINT "Press Y or N key to continue"
WHILE(1)
k = INKEY
IF(k == "y" OR k == "n") THEN EXIT
SHOWPAGE
WEND
PRINT "The response was: "; upper(k)
Yabasic
clear screen
print "Do you want to continue y/n : ";
repeat
KBD$ = lower$(inkey$)
until KBD$ = "y" or KBD$ = "n"
print KBD$
if KBD$ = "y" then
print "OK, continuing"
else
print "OK, finishing"
end if
ZX Spectrum Basic
Note that this will also work in GW-BASIC and most QBasic-compatible BASICs if all instances of "GO TO
" are changed to "GOTO
".
10 IF INKEY$<>"" THEN GO TO 10: REM flush the keyboard buffer
20 PRINT "Press Y or N to continue"
30 LET k$ = INKEY$
40 IF k$ <> "y" AND k$ <> "Y" AND k$ <> "n" AND k$ <> "N" THEN GO TO 30
50 PRINT "The response was "; k$
Batch File
@echo off
choice
if errorlevel 2 echo You chose N
if errorlevel 1 echo You chose Y
>nul pause
C
For POSIX compliant systems (in theory that includes WinNT family).
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>
void set_mode(int want_key)
{
static struct termios old, new;
if (!want_key) {
tcsetattr(STDIN_FILENO, TCSANOW, &old);
return;
}
tcgetattr(STDIN_FILENO, &old);
new = old;
new.c_lflag &= ~(ICANON);
tcsetattr(STDIN_FILENO, TCSANOW, &new);
}
int get_key(int no_timeout)
{
int c = 0;
struct timeval tv;
fd_set fs;
tv.tv_usec = tv.tv_sec = 0;
FD_ZERO(&fs);
FD_SET(STDIN_FILENO, &fs);
select(STDIN_FILENO + 1, &fs, 0, 0, no_timeout ? 0 : &tv);
if (FD_ISSET(STDIN_FILENO, &fs)) {
c = getchar();
set_mode(0);
}
return c;
}
int main()
{
int c;
while(1) {
set_mode(1);
while (get_key(0)); /* clear buffer */
printf("Prompt again [Y/N]? ");
fflush(stdout);
c = get_key(1);
if (c == 'Y' || c == 'y') {
printf("\n");
continue;
}
if (c == 'N' || c == 'n') {
printf("\nDone\n");
break;
}
printf("\nYes or no?\n");
}
return 0;
}
C#
using System;
namespace Y_or_N
{
class Program
{
static void Main()
{
bool response = GetYorN();
}
static bool GetYorN()
{
ConsoleKey response; // Creates a variable to hold the user's response.
do
{
while (Console.KeyAvailable) // Flushes the input queue.
Console.ReadKey();
Console.Write("Y or N? "); // Asks the user to answer with 'Y' or 'N'.
response = Console.ReadKey().Key; // Gets the user's response.
Console.WriteLine(); // Breaks the line.
} while (response != ConsoleKey.Y && response != ConsoleKey.N); // If the user did not respond with a 'Y' or an 'N', repeat the loop.
/*
* Return true if the user responded with 'Y', otherwise false.
*
* We know the response was either 'Y' or 'N', so we can assume
* the response is 'N' if it is not 'Y'.
*/
return response == ConsoleKey.Y;
}
}
}
C++
Windows specific
#include <conio.h>
#include <iostream>
using namespace std;
int main()
{
char ch;
_cputs( "Yes or no?" );
do
{
ch = _getch();
ch = toupper( ch );
} while(ch!='Y'&&ch!='N');
if(ch=='N')
{
cout << "You said no" << endl;
}
else
{
cout << "You said yes" << endl;
}
return 0;
}
Clojure
Note: If you run it with Leiningen, use the special trampoline run to prevent issues:
$ lein trampoline run
(ns yprompt.core
(:import jline.Terminal)
(:gen-class))
(defn yes? [k]
(if (or (= k 89) (= k 121)) true false))
(defn prompt []
(println "\nPrompt again [Y/N]?")
(let [term (Terminal/getTerminal)
ykey (yes? (.readCharacter term System/in))]
(if-not ykey
(recur)
(println "Yes!"))))
(defn -main [& args]
(prompt))
Common Lisp
LispWorks
Version 1:
(defun rosetta-y-or-n ()
(clear-input *query-io*)
(y-or-n-p))
Version 2:
(defun y-or-n ()
(clear-input *standard-input*)
(loop as dum = (format t "Y or N for yes or no: ")
as c = (read-char)
as q = (and (not (equal c #\n)) (not (equal c #\y)))
when q do (format t "~%Need Y or N~%")
unless q return (if (equal c #\y) 'yes 'no)))
Version 1 and 2 work as required in a LispWorks GUI interface, i.e. they return immediately when the y or n keys are pressed, without waiting for the Enter key.
ncurses
When called from a REPL in a Linux terminal, y-or-n-p is line buffered, which means any input has to be confirmed by an Enter key.
In order to have keys available immediately to the program, line buffering has to be disabled in the tty driver. This can be done by utilizing the ncurses terminal library available on most GNU/Linux systems. To interface ncurses from Lisp, the croatoan library can be used:
Version 3:
(defun y-or-no ()
(with-screen (scr :input-buffering nil :input-blocking t)
(clear scr)
(princ "Do you want to continue? [Y/N]" scr)
(refresh scr)
(event-case (scr event)
((#\Y #\y) (return-from event-case t))
((#\N #\n) (return-from event-case nil)))))
D
import std.stdio: stdout, write, writefln;
extern (C) nothrow {
void _STI_conio();
void _STD_conio();
int kbhit();
int getch();
}
void main() {
_STI_conio();
write("Enter Y or N: ");
stdout.flush();
int c;
do {
while(!kbhit()) {}
c = getch();
// Visual feedback for each keypress.
write(cast(char)c);
stdout.flush();
} while(c != 'Y' && c != 'y' && c != 'N' && c != 'n');
writefln("\nResponse: %c", cast(char)c);
_STD_conio();
}
- Output:
Enter Y or N: abcN Response: N
Delphi
Thanks for JensBorrisholt [1].
program Obtain_a_Y_or_N_response;
{$APPTYPE CONSOLE}
uses
System.Console;
function GetKey(acepted: string): Char;
var
key: Char;
begin
while True do
begin
if Console.KeyAvailable then
begin
key := UpCase(Console.ReadKey().KeyChar);
if pos(key, acepted) > 0 then
exit(key);
end;
end;
Result := #0; // Never Enter condition
end;
begin
Console.WriteLine('Press Y or N');
case GetKey('YN') of
'Y':
Console.WriteLine('You pressed Yes');
'N':
Console.WriteLine('You pressed No');
else
Console.WriteLine('We have a error');
end;
Readln;
end.
- Output:
Press Y ou N You pressed Yes
EGL
handler YesOrNoHandler type RUIhandler{initialUI =[ui], onConstructionFunction = start}
ui Div { };
const KEY_N int = 78;
const KEY_Y int = 89;
function start()
document.onKeyDown = d_onKeyDown;
end
function d_onKeyDown(e Event in)
case (e.ch)
when (KEY_N)
ui.innerText = "N pressed.";
when (KEY_Y)
ui.innerText = "Y pressed.";
end
e.preventDefault();
end
end
Elm
import Char
import Graphics.Element exposing (Element, empty, show)
import Keyboard
view : Int -> Element
view keyCode =
let
char =
Char.fromCode keyCode
showChar =
toString >> ((++) "The last (y/n) key pressed was: ") >> show
in
case char of
'n' ->
showChar char
'y' ->
showChar char
_ ->
empty
main : Signal Element
main =
Signal.map view Keyboard.presses
ERRE
!$KEY
................
! flush the keyboard buffer
! --------------------------------
! you can use POKE(198,0) in C-64
! ERRE version
! --------------------------------
REPEAT
GET(K$)
UNTIL K$=""
PRINT("Press Y or N to continue")
REPEAT
GET(K$)
UNTIL INSTR("YyNn",K$)<>0
!
! with C-64 you must write a line like
! UNTIL K$="Y" OR K$="N"
!
PRINT("The response was ";K$)
.................
!$KEY
is a directive pragma: using it GET
become an equivalent to Qbasic INKEY$, otherwise it's equivalent to QBasic INPUT$(1). !$KEY is also used to mantain portability with the C-64 version of ERRE language.
Euphoria
integer key
puts(1,"Your answer? (Y/N)\n")
while get_key()!=-1 do
end while
while 1 do
key = get_key()
if key!=-1 and (key = 'Y' or key = 'y' or key = 'N' or key = 'n') then
exit
end if
end while
printf(1,"Your response was %s\n",key)
F#
open System
let rec yorn () =
let rec flush () = if Console.KeyAvailable then ignore (Console.ReadKey()); flush ()
flush ()
printf "\nY or N? "
match Console.ReadKey().Key with
| ConsoleKey.Y -> 'Y'
| ConsoleKey.N -> 'N'
| _ -> yorn()
printfn "\nYour choice: %c" (yorn())
Forth
: flush ( -- ) \ discard pending input
begin key? while key drop repeat ;
: y-or-n ( c-addr u -- f )
flush begin
cr 2dup type key bl or \ note 1.
dup [char] y = swap [char] n = over or \ note 2.
if nip nip exit then
drop again ;
\ Note 1. KEY BL OR returns a lowercase letter in the case that an
\ uppercase letter was entered, an unchanged lowercase letter in the
\ case that a lowercase letter was entered, and garbage otherwise. BL
\ returns the ASCII code for a space, 32, which is incidentally the
\ "bit of difference" between ASCII uppercase and lowercase letters.
\ Note 2. this line has the stack effect ( x -- f1 f2 ), where F1 is
\ true only if x='y', and F2 is true only if x='y' OR if x='n'.
\ I think these expressions aren't too clever, but they _are_ rather
\ optimized for the task at hand. This might be more conventional:
: y-or-n ( c-addr u -- f )
flush begin
cr 2dup type key case
[char] y of 2drop true exit endof
[char] Y of 2drop true exit endof
[char] n of 2drop false exit endof
[char] N of 2drop false exit endof
endcase again ;
Fortran
Standard Fortran has no special I/O statements that allow asynchronous actions (such as the KeyPressed and ReadKey functions of Turbo Pascal), so input is awaited in the usual fashion and a prompt should be supplied to indicate to the reader that a response is awaited, otherwise the user will confront a blank screen with nothing happening and will have to guess what might be expected. Further, there is no scheme for knowing if impending input has been waiting in an input buffer since before the need for a question arose, so it is not possible to flush such lines before requesting the special input. Impatience at the screenface can prompt typing ahead so that the next command will be immediately available but incorrectly anticipated input will likely wreck the run, though for yes/no responses you may be rescued if such input does not conform to the required form: the bad input will be ignored and the question asked afresh. Thus, the details of the specification cannot be met via standard Fortran, though a given system may have special subroutines equivalent to KeyPressed, etc. available.
Even so, asking questions can often be useful when messing about with tests, etc., so some routines for this can help. These were devised afresh at the Culham Science Centre, so there was some language generality:
CHARACTER*120 FUNCTION REPLY(QUERY) !Obtain a text in reply.
Concocted by R.N.McLean (whom God preserve), December MM.
CHARACTER*(*) QUERY !The question.
CHARACTER*120 TEXT !Alas, oh for proper strings.
INTEGER MSG,KEYS,LSTNB !Let's hope everyone has the same type.
COMMON /IOUNITS/ MSG,KEYS!Orifices.
WRITE (MSG,1) QUERY(1:LSTNB(QUERY)),"?"!So, splurt.
1 FORMAT (2A,$) !A trailing text literal may not be rolled.
READ (KEYS,1) TEXT !Dare not use REPLY itself. Some implementations bungle.
REPLY = TEXT !So, shuffle.
RETURN !Take that.
END !Others interpret the reply.
REAL*8 FUNCTION REPLYN(QUERY) !Obtain a number in reply.
Concocted by R.N.McLean (whom God preserve), December MM.
CHARACTER*(*) QUERY !The question.
REAL X !The answer, presumably not 42.
INTEGER MSG,KEYS,LSTNB !Let's hope everyone has the same type.
COMMON /IOUNITS/ MSG,KEYS!Orifices.
1 WRITE (MSG,2) QUERY(1:LSTNB(QUERY)) !No trailing spaces.
2 FORMAT (A,$) !The $ obviously suppresses the newline.
READ (KEYS,*,ERR = 3) X !Presume adequate testing for now.
REPLYN = X !The value!
RETURN !All done.
3 WRITE (MSG,4) !Or perhaps not.
4 FORMAT ('Distasteful number. Try again...') !All sorts of ways.
GO TO 1 !My patience is unconditional.
END !One way or another, a number will be secured.
LOGICAL FUNCTION YEA(QUERY) !Obtain a Yes in reply?
Concocted by R.N.McLean (whom God preserve), December MM.
CHARACTER*(*) QUERY !The question.
CHARACTER*120 WHAT,REPLY !Quite so.
CHARACTER*1 C !Scratchpad.
INTEGER MSG,KEYS !Let's hope everyone has the same type.
COMMON /IOUNITS/ MSG,KEYS!Orifices.
INTEGER L !A finger.
1 WHAT = REPLY(QUERY) !So, get an answer.
DO L = 1,LEN(WHAT) !Sigh. Oh for Trim(string)
C = WHAT(L:L) !Sniff a CHARACTER.
IF (C .NE. ' ') GO TO 10 !A starter?
END DO !No. Try further on.
WRITE (MSG,2) !Surely not.
2 FORMAT ('All blank?') !Poke.
3 WRITE (MSG,4) !Sigh.
4 FORMAT ('I dig it not. Try Yes/Si/Da/Oui/Ja, or No')
GO TO 1 !Get it right, this time?
10 IF (INDEX('YySsDdOoJj',C) .GT. 0) THEN !Yes/Si/Da/Oui/Ja...
YEA = .TRUE. !A decision.
ELSE IF (INDEX('Nn',C) .GT. 0) THEN !No,No,Nyet,Non...
YEA = .FALSE. !Even if negative.
ELSE !But if unrecognised,
GO TO 3 !Try again.
END IF !So much for choices.
RETURN !Pass the word.
END !Enough of yes-beings.
LOGICAL FUNCTION NAY(QUERY) !Perhaps this reads better.
Concocted by R.N.McLean (whom God preserve), December MM.
CHARACTER*(*) QUERY !The question.
LOGICAL YEA !Let us hope so.
NAY = .NOT.YEA(QUERY) !Straightforward.
RETURN !Pass the inverted word.
END !So much for naysayers.
Usage might be something like IF (NAY("Keep the results")) CALL PURGE
FreeBASIC
' FB 1.05.0 Win64
While InKey <> "" : Wend '' flush keyboard buffer
Print "Do you want to continue y/n : ";
Dim answer As String
Do
answer = LCase(Inkey)
Loop Until answer = "y" OrElse answer = "n"
Print answer '' echo response to console
If answer = "y" Then
Print "OK, continuing"
Else
Print "OK, finishing"
End If
Sleep
Sample input/output:
- Output:
Do you want to continue y/n : y OK, continuing
FutureBasic
void local fn DoDialog( ev as long )
CFStringRef key
select ( ev )
case _windowKeyDown
cls
key = fn EventCharacters
select ( lcase(key) )
case @"y",@"n"
printf @"You pressed the \"%@\" key",key
DialogEventSetBool(YES)// we handled the event
end select
end select
end fn
subclass
window 1, @"Press \"Y\" or \"N\" keys", (0,0,550,400)
on dialog fn DoDialog
HandleEvents
GlovePIE
if var.end=0 then
var.end=0
debug="Press the Y key or the N key to continue:"
endif
if pressed(Key.Y)and var.end=0 then
var.end=1
debug="You pressed the Y key."
endif
if pressed(Key.N)and var.end=0 then
var.end=1
debug="You pressed the N key."
endif
Go
package main
import (
"log"
gc "code.google.com/p/goncurses"
)
func main() {
s, err := gc.Init()
if err != nil {
log.Fatal("init:", err)
}
defer gc.End()
var k gc.Key
for {
gc.FlushInput()
s.MovePrint(20, 0, "Press y/n ")
s.Refresh()
switch k = s.GetChar(); k {
default:
continue
case 'y', 'Y', 'n', 'N':
}
break
}
s.Printf("\nThanks for the %c!\n", k)
s.Refresh()
s.GetChar()
}
package main // siongui.github.io/2016/04/23/go-read-yes-no-from-console import ( "fmt" "strings" ) func ask() bool { var s string fmt.Printf("(y/n): ") fmt.Scan(&s) s = strings.TrimSpace(s) s = strings.ToLower(s) if s == "y" || s == "yes" { return true } return false } func main() { ans := ask() if ans { fmt.Println("yes") } else { fmt.Println("no") } }
GW-BASIC
10 IF INKEY$<>"" THEN GOTO 10: REM flush the keyboard buffer
20 PRINT "Press Y or N to continue"
30 LET k$ = INKEY$
40 IF k$ <> "y" AND k$ <> "Y" AND k$ <> "n" AND k$ <> "N" THEN GOTO 30
50 PRINT "The response was "; k$
Haskell
This may not be very idiomatic; it's pretty monad-oriented, and the use of do expressions makes the whole thing feel rather imperative.
import System.IO
hFlushInput :: Handle -> IO ()
hFlushInput hdl = do
r <- hReady hdl
if r then do
c <- hGetChar hdl
hFlushInput hdl
else
return ()
yorn :: IO Char
yorn = do
c <- getChar
if c == 'Y' || c == 'N' then return c
else if c == 'y' then return 'Y'
else if c == 'n' then return 'N'
else yorn
main :: IO ()
main = do
hSetBuffering stdout NoBuffering
putStr "Press Y or N to continue: "
hSetBuffering stdin NoBuffering
hSetEcho stdin False
hFlushInput stdin
answer <- yorn
putStrLn [answer]
Icon and Unicon
This solution works in both Icon and Unicon. It also accepts y or n.
procedure main()
write("Response was ",getResponse("OK? (Y or N): "))
end
procedure getResponse(prompt)
while kbhit() do getch() # flush input
writes(prompt)
repeat if map(answer := getch()) == ("y"|"n") then break
return answer
end
Inform 7
Keyboard input goes through a virtual machine that's only required to provide blocking input operations, so flushing the buffer isn't possible.
Inform 7 has a built-in function to ask the user for yes-or-no input, but it requires them to press enter afterward:
Qwantz is a room.
When play begins:
say "A wizard has turned you into a whale. Is this awesome (Y/N)? ";
if the player consents, say "Awesome!";
end the story.
To read a single key without waiting for enter, we can redefine the function by including a snippet of Inform 6 code:
To decide whether player consents: (- (YesOrNoKey()) -).
Include (-
[ YesOrNoKey ch;
do { ch = VM_KeyChar(); } until (ch == 'y' or 'Y' or 'n' or 'N');
return ch == 'y' or 'Y';
]; -).
Java
The task specification that there should be no need for the user to press the enter key, creates an awkward situation for the Java language.
However, a short program that waits for the user to press return can easily be constructed.
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.awt.EventQueue;
import java.awt.event.KeyAdapter;
import javax.swing.JFrame;
public final class KeyboardInputObtainYOrN {
public static void main(String[] aArgs) {
EventQueue.invokeLater( () -> { new Test("Obtain Y or N"); } );
}
}
final class Test extends JFrame {
public Test(String aTitle) {
super(aTitle);
addKeyListener( new YesOrNoKeyAdapter() );
setVisible(true);
try {
while ( System.in.available() > 0 ) {
System.in.read();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Do you want to quit the program? Y / N");
}
}
final class YesOrNoKeyAdapter extends KeyAdapter {
@Override
public void keyPressed(KeyEvent aKeyEvent) {
if ( aKeyEvent.getKeyCode() == KeyEvent.VK_Y ) {
System.out.println("Y was pressed, quitting the program");
Runtime.getRuntime().exit(0);
} else if ( aKeyEvent.getKeyCode() == KeyEvent.VK_N ) {
System.out.println("N was pressed, but the program is about to end anyway");
Runtime.getRuntime().exit(0);
} else {
System.out.println("Please try again, only Y or N are acceptable");
}
}
}
JavaScript
Here's a synchronous ES6 implementation. The synchronous code must be executed in an async function definition. In this example, `wait_key` returns the key pressed and `done` must be called decouple the listening to stdin and end the process. The example pauses for a second to show that the keys pressed before `wait_key` is called are not heard.
const readline = require('readline');
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
var wait_key = async function() {
return await new Promise(function(resolve,reject) {
var key_listen = function(str,key) {
process.stdin.removeListener('keypress', key_listen);
resolve(str);
}
process.stdin.on('keypress', key_listen);
});
}
var done = function() {
process.exit();
}
var go = async function() {
do {
console.log('Press any key...');
var key = await wait_key();
console.log("Key pressed is",key);
await new Promise(function(resolve) { setTimeout(resolve,1000); });
} while(key != 'y');
done();
}
go();
Here's how you can asynchronously read a single character in Node.js, using the keypress
package.
This does not seem to be possible to do synchronously in Node.js or at all in the SpiderMonkey shell.
var keypress = require('keypress');
keypress(process.stdin);
process.stdin.on('keypress', function (ch, key) {
if (key && (key.name === 'y' || key.name === 'n')) {
console.log('Reply:' + key.name);
}
});
process.stdin.setRawMode(true);
process.stdin.resume();
Using DOM events.
document.body.addEventListener('keyup', function (e) {
var key = String.fromCharCode(e.keyCode).toLowerCase();
if (key === 'y' || key === 'n') {
console.log('response is: ' + key);
}
}, false);
Julia
Uses the Gtk library.
using Gtk.ShortNames
function keypresswindow()
# This code creates the Gtk widgets on the screen.
txt = "Type Y or N"
win = Window("Keypress Test", 250, 30) |> (Frame() |> ((vbox = Box(:v)) |> (lab = Label(txt))))
# this is the keystroke processing code, a function and a callback for the function.
function keycall(w, event)
ch = Char(event.keyval)
set_gtk_property!(lab,:label, ch in('n','N','y','Y') ? "You hit the $ch key." : txt)
end
Gtk.signal_connect(keycall, win, "key-press-event")
# this code sets up a proper exit when the widow is closed.
c = Condition()
endit(w) = notify(c)
Gtk.signal_connect(endit, win, :destroy)
Gtk.showall(win)
wait(c)
end
keypresswindow()
Kotlin
// version 1.0.6
import java.awt.event.KeyAdapter
import java.awt.event.KeyEvent
import javax.swing.JFrame
import javax.swing.SwingUtilities
class Test: JFrame() {
init {
while (System.`in`.available() > 0) System.`in`.read()
println("Do you want to quit Y/N")
addKeyListener(object: KeyAdapter() {
override fun keyPressed(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_Y) {
println("OK, quitting")
quit()
} else if (e.keyCode == KeyEvent.VK_N) {
println("N was pressed but the program is about to end anyway")
quit()
} else {
println("Only Y/N are acceptable, please try again")
}
}
})
}
private fun quit() {
isVisible = false
dispose()
System.exit(0)
}
}
fun main(args: Array<String>) {
SwingUtilities.invokeLater {
val f = Test()
f.isFocusable = true
f.isVisible = true
}
}
Liberty BASIC
nomainwin
open "Y/N" for graphics_nsb_nf as #1
#1 "trapclose Quit"
#1 "down;setfocus;when characterInput KeyCheck"
#1 "place 10 50;\Press Y or N"
Inkey$=""
wait
sub KeyCheck hndle$,k$
k$=upper$(k$)
#hndle$ "cls;place 10 50"
select case k$
case "Y"
#hndle$ "\ Yes"
case "N"
#hndle$ "\No"
case else
#hndle$ "\Incorrect input. Press Y or N"
end select
end sub
sub Quit hndle$
close #hndle$
end
end sub
LiveCode
In the Card script, add a handler for the OpenCard event, putting empty into the text field.
In the text field, put the following in its code
on KeyDown k
if toUpper(k) is among the items of "Y,N" then
answer "Thanks for your response"
else
answer "You need to enter Y or N"
end if
put empty into me
end KeyDown
n.b. This sort of confirmation in GUI apps is usually presented as a dialog box with Yes/No buttons, which automatically handles keyboard input.
Logo
to yorn
type [Press Y or N to continue: ]
local "clear
make "clear readchars 0 ; clear input buffer
local "yorn
do.until [make "yorn readchar] [or equal? :yorn "Y equal? :yorn "N]
print :yorn
output :yorn
end
M2000 Interpreter
Simple Loop using Key$
If keyboard is Greek the we have to change to English. Other examples use Keyboard codes.
Module Simple {
\\ a small modification from BBC BASIC entry
REPEAT {} UNTIL INKEY$ = ""
PRINT "Press Y or N to continue"
REPEAT {
k$ =Ucase$(Key$)
} UNTIL K$="Y" OR k$="N"
PRINT "The response was "; k$
}
Simple
Use a Function to return keypress and by reference return value
Module Checkit {
Function GetYN$ (&Ret) {
const Y=0x59
const N=0x4E
Ret=False
Do {
if keypress(Y) then Ret=True : exit
if keypress(N) then exit
drop$=inkey$
} Always
K$=key$
do {} until filter$(Inkey$,k$)=""
=Ucase$(K$)
}
keyboard "abcde" ' feed keyboard (inkey$ get these characters)
Y=0
Print "Your answer (Y/N):"; GetYN$(&Y)
Print Y
}
Checkit
Using Thread to read/write Keyboard buffer
We use a thread, using after, for one run, after 10ms, when Input wait for keypress. So when call to GetYN module exit has Y or N with Enter to keyboard. Now Input finish.
Threads runs in same namespace as the module they created. So module name and Y variable are visible.Module GetYN can't read parent module variables, except M which declared as GLOBAL. After 500ms N is returned.
Using Profiler and Print Timecount we get the real duration (using high resolution timer), of response.
Module CheckisToo {
Module GetYN (&Ret) {
const Y=0x59
const N=0x4E
Ret=False
Do {
If M>50 then Keyboard "N" : exit
if keypress(Y) then Ret=True : exit
if keypress(N) then exit
drop$=inkey$
\\ ensure thread MM run using wait
wait 1
} Always
Keyboard Ucase$(Key$)+Chr$(13)
}
keyboard "abcde"
Y=0
Global M=0
Thread {
M++
} as MM interval 10
While Inkey$<>"" {}
After 10 {
Module GetYN &Y
}
Profiler
Input "Your answer (Y/N):", A$
Print timecount
Print Y, M
Threads Erase
}
CheckisToo
Using User Form (GUI)
Module UseUIForm {
Const Y=0x59, N=0x4E, Center=2
Ret=False
Declare Form1 form
Layer Form1 {
Window 22, 8000, 4000;
Cls #333333,0
Cursor 0, Height/2
Report Center, "Press (Y/N)"
}
Function form1.Keydown {
Read New &key, &shiftKey
IF key=Y then ret=True : Method Form1, "CloseNow"
If key=N Then Method Form1, "CloseNow"
}
Method Form1, "Show", 1 ' modal show
Print Ret
Declare Form1 Nothing
}
UseUIForm
Mathematica /Wolfram Language
CreateDialog[TextCell["Yes or no?[Y/N]"],
NotebookEventActions -> {
"KeyDown" :> Switch[ToUpperCase@CurrentValue["EventKey"],
"Y", Print["You said yes"]; DialogReturn[],
"N", Print["You said no"]; DialogReturn[]
]}];
Microsoft Small Basic
Submitted by: AykayayCiti (Earl L. Montgomery) on Mar 19, 2018. Once you hit a key a separate dialog box will appear. Place them side by side to see the results.
'From:
'Andy Oneill, 2-6-2015, "Small Basic: Key Input,
'" TechNet, https://social.technet.microsoft.com/wiki/contents/articles/29850.small-basic-key-input.aspx, accessed 3-19-2018
GraphicsWindow.DrawText(10, 10, "Hit any key to dump.")
GraphicsWindow.KeyDown = OnKeyDown
Sub OnKeyDown
TextWindow.WriteLine(GraphicsWindow.LastKey)
EndSub
MiniScript
Access to hardware like the keyboard is very dependent on the host app, but here's a version that works with MiniMicro, a standardized MiniScript virtual machine.
// flush the keyboard
while key.available
key.get
end while
// and now prompt and wait for Y or N
print "Press Y or N:"
k = ""
while k != "Y" and k != "N"
k = key.get.upper
end while
print "You pressed: " + k
MUMPS
Version from terminal shown below.
for read !,"Enter Y or N to continue: ",input quit:input?1(1"Y",1"y",1"N",1"n")
- Output:
Enter Y or N to continue: JEnter Y or N to continue: YES Enter Y or N to continue: no Enter Y or N to continue: N
SAMPLES>
NetRexx
/* NetRexx */
options replace format comments java crossref savelog symbols binary
Say 'Please enter Y or N'
parse ask c
Select
when c='Y' Then Say 'YES'
when c='N' Then Say 'NO'
otherwise Say 'Undecided'
End
Nim
Using "gintro" bindings to Gtk3.
import strformat
import gintro/[glib, gobject, gtk, gio]
import gintro/gdk except Window
#---------------------------------------------------------------------------------------------------
proc onKeyPress(window: ApplicationWindow; event: Event; label: Label): bool =
var keyval: int
if not event.getKeyval(keyval): return false
if keyval in [ord('n'), ord('y')]:
label.setText(&"You pressed key '{chr(keyval)}'")
result = true
#---------------------------------------------------------------------------------------------------
proc activate(app: Application) =
## Activate the application.
let window = app.newApplicationWindow()
window.setTitle("Y/N response")
let hbox = newBox(Orientation.horizontal, 0)
window.add(hbox)
let vbox = newBox(Orientation.vertical, 10)
hbox.packStart(vbox, true, true, 20)
let label1 = newLabel(" Press 'y' or 'n' key ")
vbox.packStart(label1, true, true, 5)
let label2 = newLabel()
vbox.packStart(label2, true, true, 5)
discard window.connect("key-press-event", onKeyPress, label2)
window.showAll()
#———————————————————————————————————————————————————————————————————————————————————————————————————
let app = newApplication(Application, "Rosetta.YNResponse")
discard app.connect("activate", activate)
discard app.run()
NS-HUBASIC
10 PRINT "PRESS Y OR N TO CONTINUE."
20 IF INKEY$<>"Y" AND INKEY$<>"N" THEN GOTO 20
30 PRINT "THE RESPONSE WAS ";INKEY$;"."
OCaml
Unix
module, exposing POSIX interfaces like termios, is normally bundled with any standard OCaml distribution. Utilizing termios is the solution many other language examples here went with.
OCaml needs to link to the bundled unix archives correctly in order to compile / run code that uses definitions within the module. To do this with the plain OCaml toolchain, remember to add the library archive to the commandline like so:
ocaml unix.cma <yourfile.ml>
interpreted
ocamlc -o <progname> unix.cma <yourfile.ml>
bytecode executable
ocamlopt -o <progname> unix.cmxa <yourfile.ml>
native executable
Here we define some helper functions that we'll use:
let attrs = Unix.(tcgetattr stdin)
let buf = Bytes.create 1
let prompt switch =
Unix.(tcsetattr stdin TCSAFLUSH)
@@ if switch then { attrs with c_icanon = false } else attrs
let getchar () =
let len = Unix.(read stdin) buf 0 1 in
if len = 0 then raise End_of_file else Bytes.get buf 0
Now the main program:
let rec loop () =
print_string "Prompt? [Y/N]: "; flush stdout;
loop
@@ print_endline
@@ match getchar () with
| 'n' | 'N' -> raise Exit
| 'y' | 'Y' -> ": Ok."
| _ -> ": Invalid."
let _ = try loop @@ prompt true with Exit | End_of_file -> prompt false
Oforth
import: console
: YorN
| c |
System.Console flush
doWhile: [
System.Console receiveChar toUpper ->c
c 'Y' <> c 'N' <> and
]
c ;
OpenEdge/Progress
DEF VAR lanswer AS LOGICAL INITIAL ?.
DO WHILE lanswer = ?:
READKEY.
IF CHR( LASTKEY ) = "n" OR CHR( LASTKEY ) = "y" THEN
lanswer = CHR( LASTKEY ) = "y".
END.
MESSAGE lanswer VIEW-AS ALERT-BOX.
PARI/GP
GP's input
is not able to read an unbuffered single character, so one must use PARI where the solution is identical to that of C.
Pascal
Program ObtainYN;
uses
crt;
var
key: char;
begin
write('Your answer? (Y/N): ');
repeat
key := readkey;
until (key in ['Y', 'y', 'N', 'n']);
writeln;
writeln ('Your answer was: ', key);
end.
Output:
% ./ObtainYN Your answer? (Y/N): Your answer was: y
Perl
use Term::ReadKey;
ReadMode 4; # change to raw input mode
my $key = '';
while($key !~ /(Y|N)/i) {
1 while defined ReadKey -1; # discard any previous input
print "Type Y/N: ";
$key = ReadKey 0; # read a single character
print "$key\n";
}
ReadMode 0; # reset the terminal to normal mode
print "\nYou typed: $key\n";
Phix
For 1970s-style character console (/beginner) applications:
integer key while get_key()!=-1 do end while -- flush puts(1,"Your answer? (Y/N)") while 1 do key = upper(get_key()) if find(key,"YN") then exit end if end while printf(1,"\nYour response was %s\n",key)
For GUI (graphical user interface) applications, use something more like this:
function key_cb(Ihandle /*ih*/, atom c) if lower(c)='y' then y_keyed() end if if lower(c)='n' then n_keyed() end if return IUP_CONTINUE end function IupSetCallback(dlg, "K_ANY", Icallback("key_cb"))
See Keyboard_macros#Phix or Conway's_Game_of_Life#Phix for a more complete example
PicoLisp
(de yesno ()
(loop
(NIL (uppc (key)))
(T (= "Y" @) T)
(T (= "N" @)) ) )
PL/I
yn: Proc Options(main):
Dcl sysin stream input;
Dcl sysprint stream output;
Dcl c Char(1);
Put Skip List('Please enter Y or N');
Get Edit(c)(a(1));
Select(c);
When('Y','y','J','j')
Put Skip List('YES');
When('N','n')
Put Skip List('NO');
Otherwise
Put Skip List('Undecided?');
End;
End;
PowerShell
This is for console use only. The ISE is geared for a different type of input.
do
{
$keyPress = [System.Console]::ReadKey()
}
until ($keyPress.Key -eq "Y" -or $keyPress.Key -eq "N")
$keyPress | Format-Table -AutoSize
If the user pressed the "Y" key...
- Output:
KeyChar Key Modifiers ------- --- --------- y Y 0
If the user pressed the "N" key...
- Output:
KeyChar Key Modifiers ------- --- --------- n N 0
PureBasic
Inkey() returns the character string of the key which is being pressed at the time.
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$)
Python
#!/usr/bin/env python
try:
from msvcrt import getch
except ImportError:
def getch():
import sys, tty, termios
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return ch
print "Press Y or N to continue"
while True:
char = getch()
if char.lower() in ("y", "n"):
print char
break
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from curses import wrapper
#
#
def main(stdscr):
# const
#y = ord("y")
#n = ord("n")
while True:
# keyboard input interceptor|listener
#window.nodelay(yes)
# - If yes is 1, getch() will be non-blocking.
# return char code
#kb_Inpt = stdscr.getch()
# return string
kb_Inpt = stdscr.getkey()
#if kb_Inpt == (y or n):
if kb_Inpt.lower() == ('y' or 'n'):
break
return None
#
return None
#
#*** unit test ***#
if __name__ == "__main__":
#
wrapper(main)
QB64
CBTJD: 2020/03/15
WHILE INKEY$ <> "": WEND ' Flushes keyboard buffer.
PRINT "Do you want to continue? (Y/N)"
DO
k$ = UCASE$(INKEY$) ' Forces key response to upper case.
LOOP UNTIL k$ = "Y" OR k$ = "N"
PRINT "You pressed " + CHR$(34) + k$ + CHR$(34) + "." ' CHR$(34) prints quotation marks.
QUACKASM
Note: The following is not a full program (it is only a subroutine, using standard calling conventions), nor does it flush the keyboard buffer (there is no standard way to do this in QUACKVM; it may be possible using extensions, but none are currently defined).
; Stores result in cell 2; 1 if yes, 0 if no.
:YORN
PRINT YORNMSG
:YORN1
INPUT >2
AND *2,$5F,'Y >2 /YORN2
AND *2,,'N \YORN1
:YORN2
PRINTC *2
PRINTC 13
AND *2,1 >2
RETURN
:YORNMSG " (Y/N)? \
Racket
#lang racket
;; GUI version
(require racket/gui)
(message-box "Yes/No example" "Yes or no?" #f '(yes-no))
;; Text version, via stty
(define stty
(let ([exe (find-executable-path "stty")])
(λ args (void (apply system* exe args)))))
(define tty-settings (string-trim (with-output-to-string (λ() (stty "-g")))))
(printf "Yes or no? ") (flush-output)
(stty "-icanon" "-echo" "min" "1")
(let loop () (when (char-ready?) (loop)))
(let loop ()
(define ch (read-char))
(case (char-downcase ch)
[(#\y #\Y #\n #\N) (displayln ch) (if (memq ch '(#\y #\Y)) 'yes 'no)]
[else (loop)]))
(stty tty-settings)
Raku
(formerly Perl 6)
my $TTY = open("/dev/tty");
sub prompt-char($prompt) {
ENTER shell "stty raw -echo min 1 time 1";
LEAVE shell "stty sane";
print $prompt;
$TTY.read(1).decode('latin1');
}
say so prompt-char("Y or N? ") ~~ /:i y/;
REXX
version for all classic REXXes
This version works with all classic REXXes.
REXX (in general) requires the user to press the ENTER key after entering text.
This is because the original (IBM) REXX was designed and written for a system when all I/O to a user's terminal screen was
in block mode and required the user to press one of the following before any data was sent to the computer:
- the ENTER key
- a PF (program function key)
- a PA (program assist key)
- the ATTN (attention) key
- possibly some other special key(s)
Note that the above keys may have different names on terminals that emulate an IBM 3270 type terminal (block mode terminals).
Some older Classic REXX interpreters have a keyboard read subroutine (BIF) so that the program can read keyboard keys as
they are pressed (see the other versions below).
/*REXX program tests for a Y or N key when entered from keyboard after a prompt.*/
do queued(); pull; end /*flush the stack if anything is queued*/
prompt = 'Please enter Y or N for verification:' /*this is the PROMPT message.*/
do until pos(ans,'NY')\==0 & length(ans)==1 /*keep looking for a Y or N answer.*/
say; say prompt /*display blank line; display prompt. */
pull ans /*get the answer(s) and uppercase it.*/
ans=space(ans, 0) /*elide all blanks. */
end /*until*/
/*stick a fork in it, we're all done. */
version 1 for PC/REXX and Personal REXX
This version of a REXX program works with PC/REXX and Personal REXX.
/*REXX program tests for a Y or N key when entered from keyboard after a prompt.*/
prompt = 'Please enter Y or N for verification:' /*this is the PROMPT message.*/
do until pos(ans, 'NYny') \== 0 /*keep prompting until answer= Y N y n */
say; say prompt /*display blank line; display prompt. */
ans=inKey('wait') /*get the answer(s) from the terminal. */
end /*until*/
/*stick a fork in it, we're all done. */
version 2 for PC/REXX and Personal REXX
This version is the same as above, but has a more idiomatic technique for testing the response.
/*REXX program tests for a Y or N key when entered from keyboard after a prompt.*/
prompt = 'Please enter Y or N for verification:' /*this is the PROMPT message.*/
do until pos(ans, 'NY')\==0 /*keep prompting 'til user answers Y│N */
say; say prompt /*display blank line; display prompt. */
ans=inKey('wait'); upper ans /*get the answer(s); and uppercase it.*/
end /*until*/
/*stick a fork in it, we're all done. */
Ring
while true
give c
if c = "Y" see "You said yes!" + nl
but c = "N" see "You said no!" + nl
else see "Try again!" + nl ok
end
RPL
≪ "Yes or No?" 1 DISP DO DO UNTIL KEY END UNTIL "YN" SWAP POS END "YN" LAST DUP SUB CLMF ≫ ´TASK’ STO
Ruby
def yesno
begin
system("stty raw -echo")
str = STDIN.getc
ensure
system("stty -raw echo")
end
if str == "Y"
return true
elsif str == "N"
return false
else
raise "Invalid character."
end
end
Ruby provides the io/console module since version 2.0:
require 'io/console'
def yesno
case $stdin.getch
when "Y" then true
when "N" then false
else raise "Invalid character."
end
end
Run BASIC
[loop] cls ' Clear screen
html "Click Y or N" ' no other options
button #y, "Y", [Y] ' they either click [Y]
button #n, "N", [N] ' or they click [N]
html "<br>";msg$ ' print message showing what they entered
wait
[Y] msg$ = "You entered [Y]es": goto [loop]
[N] msg$ = "You entered [N]o" : goto [loop]
Rust
//cargo-deps: ncurses
extern crate ncurses;
use ncurses::*;
fn main() {
initscr();
loop {
printw("Yes or no? ");
refresh();
match getch() as u8 as char {
'Y'|'y' => {printw("You said yes!");},
'N'|'n' => {printw("You said no!");},
_ => {printw("Try again!\n"); continue;},
}
break
}
refresh();
endwin();
}
Scala
println(if (scala.io.StdIn.readBoolean) "Yes typed." else "Something else.")
import java.io.InputStreamReader
val in = new InputStreamReader(System.in)
if (Seq(121, 89, 110, 78).contains(in.read()) ) {println("Yes|No")} else {println("other")}
import scala.io.{Source, BufferedSource}
val kbd_In: BufferedSource = Source.stdin
//kbd_In.next()
//res?: Char = 'y' not :String = "y"
if (Seq('y', 'Y', 'n', 'Y').contains(kbd_In.next()) ) {println("Typed y|Y|n|N")} else {println("other key")}
Seed7
$ include "seed7_05.s7i";
include "keybd.s7i";
const func boolean: yesOrNo (in string: prompt) is func
result
var boolean: yes is FALSE;
local
var char: answer is ' ';
begin
while inputReady(KEYBOARD) do
ignore(getc(KEYBOARD));
end while;
write(prompt);
repeat
answer := lower(getc(KEYBOARD));
until answer in {'y', 'n'};
yes := answer = 'y';
end func;
const proc: main is func
begin
writeln(yesOrNo("Press Y or N to continue "));
end func;
Sidef
func prompt_yn {
static rk = frequire('Term::ReadKey');
rk.ReadMode(4); # change to raw input mode
var key = '';
while (key !~ /[yn]/i) {
while (rk.ReadKey(-1) != nil) {}; # discard any previous input
print "Type Y/N: ";
say (key = rk.ReadKey(0)); # read a single character
}
rk.ReadMode(0); # reset the terminal to normal mode
return key.uc;
}
var key = prompt_yn();
say "You typed: #{key}";
- Output:
Type Y/N: a Type Y/N: b Type Y/N: c Type Y/N: y You typed: Y
SparForte
As a structured script.
#!/usr/local/bin/spar
pragma annotate( summary, "yorn" );
pragma annotate( description, "Obtain a valid Y or N response from the keyboard. The" );
pragma annotate( description, "keyboard should be flushed, so that any outstanding keypresses" );
pragma annotate( description, "are removed, preventing any existing Y or N keypress from" );
pragma annotate( description, "being evaluated. The response should be obtained as soon as" );
pragma annotate( description, "Y or N are pressed, and there should be no need to press an" );
pragma annotate( description, "enter key. " );
pragma annotate( see_also, "http://rosettacode.org/wiki/Keyboard_Input/Obtain_a_Y_or_N_response" );
pragma annotate( author, "Ken O. Burtch" );
pragma ada_95;
pragma restriction( no_external_commands );
procedure yorn is
answer : character;
begin
put( "Your answer? (Y/N) " );
loop
answer := inkey;
case answer is
when 'Y'|'y' =>
answer := 'Y';
exit;
when 'N'|'n' =>
answer := 'N';
exit;
when others =>
null;
end case;
end loop;
put_line( answer );
end yorn;
Tcl
Using the console (expects U*Xish stty)
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)"]
Without a console (answer in the global variable yn; this should work in any GUI for which there is a TCL):
proc yesno {message} {
toplevel .msg
pack [label .msg.l -text "$message\n (type Y/N)?"]
set ::yn ""
bind .msg <Key-y> {set ::yn "Y"}
bind .msg <Key-n> {set ::yn "N"}
vwait ::yn
destroy .msg
}
yesno "Do you like programming?"
TXR
This works not only on Unix-like platforms, but also on Microsoft Windows, because TXR is ported to Windows using a modified version of Cygwin.
(with-resources ((tio-orig (tcgetattr) (tcsetattr tio-orig)))
(let ((tio (copy tio-orig)))
tio.(go-raw)
(tcsetattr tio tcsaflush) ;; third arg optional, defaults to tcsadrain
(whilet ((k (get-char))
((not (member k '(#\y #\n #\Y #\N))))))))
The go-raw
method on the termios
structure only manipulates the structure contents; tcsetattr
pushes it down to the TTY driver.
go-raw
is defined in the TXR standard library like this:
(defmeth termios go-raw (tio)
tio.(clear-iflags ignbrk brkint parmrk istrip inlcr igncr icrnl ixon)
tio.(clear-oflags opost)
tio.(clear-cflags csize parenb)
tio.(clear-lflags echo echonl icanon isig)
(if (boundp 'iexten)
tio.(clear-lflags iexten))
tio.(set-cflags cs8)
(set tio.[cc vmin] 1)
(set tio.[cc vtime] 0))
UNIX Shell
getkey() {
local stty="$(stty -g)"
trap "stty $stty; trap SIGINT; return 128" SIGINT
stty cbreak -echo
local key
while true; do
key=$(dd count=1 2>/dev/null) || return $?
if [ -z "$1" ] || [[ "$key" == [$1] ]]; then
break
fi
done
stty $stty
echo "$key"
return 0
}
yorn() {
echo -n "${1:-Press Y or N to continue: }" >&2
local yorn="$(getkey YyNn)" || return $?
case "$yorn" in
[Yy]) echo >&2 Y; return 0;;
[Nn]) echo >&2 N; return 1;;
esac
}
Cleaner version using bash built-ins
#!/bin/bash
yorn() {
echo -n "${1:-Press Y or N to continue: }"
shopt -s nocasematch
until [[ "$ans" == [yn] ]]
do
read -s -n1 ans
done
echo "$ans"
shopt -u nocasematch
}
yorn
VB-DOS
OPTION EXPLICIT
DIM T AS INTEGER
T = MSGBOX("Click on yes or no", 4, "Option")
PRINT "The response is ";
IF T = 6 THEN PRINT "yes"; ELSE PRINT "no";
PRINT "."
END
Vedit macro language
Key_Purge() // flush keyboard buffer
do {
#1 = Get_Key("Are you sure? (Y/N): ") // prompt for a key
#1 &= 0xdf // to upper case
} while (#1 != 'Y' && #1 != 'N')
V (Vlang)
import term.ui as tui
struct App {
mut:
tui &tui.Context = 0
}
fn event(e &tui.Event, x voidptr) {
mut app := &App(x)
app.tui.clear()
app.tui.set_cursor_position(0, 0)
app.tui.write('V term.input event viewer (type `y`, `Y`, `n`, or `N` to exit)\n\n')
if e.typ == .key_down {
mut cap := ''
if !e.modifiers.is_empty() && e.modifiers.has(.shift) {
cap = 'capital'
}
match e.code {
.y {
app.tui.write('You typed $cap y')
}
.n {
app.tui.write('You typed $cap n')
}
else {
app.tui.write("You didn't type n or y")
}
}
}
app.tui.flush()
if e.typ == .key_down && (e.code == .y || e.code==.n) {
exit(0)
}
}
fn main() {
mut app := &App{}
app.tui = tui.init(
user_data: app
event_fn: event
window_title: 'V term.ui event viewer'
hide_cursor: true
capture_events: true
frame_rate: 60
use_alternate_buffer: false
)
println('V term.input event viewer (type `y`, `Y`, `n`, or `N` to exit)\n\n')
app.tui.run()?
}
Wee Basic
print 1 "Enter Y for yes, or N for no. (not case sensitive)"
let loop=0
let keycode=0
while loop=0
let keycode=key()
if keycode=121
let response$="y"
let loop=1
elseif keycode=89
let response$="Y"
let loop=1
elseif keycode=110
let response$="n"
let loop=1
elseif keycode=78
let response$="N"
let loop=1
endif
wend
print 1 "You entered"+response$
end
Wren
import "io" for Stdin, Stdout
Stdin.isRaw = true // input is neither echoed nor buffered in this mode
System.print("Press Y or N")
Stdout.flush()
var byte
while ((byte = Stdin.readByte()) && !"YNyn".bytes.contains(byte)) {}
var yn = String.fromByte(byte)
System.print(yn)
Stdin.isRaw = false
- Output:
Sample run:
Press Y or N y
XPL0
include c:\cxpl\codes; \intrinsic 'code' declarations
loop [OpenI(1); \flush any pending keystroke
case ChIn(1) of \get keystroke
^Y,^y: Text(0, "yes");
^N,^n: Text(0, "no");
$1B: quit \Esc key terminates program
other ChOut(0, 7\bel\);
CrLf(0);
]
Z80 Assembly
This simple template can be CALL
ed to wait for a Y/N response and act based on that. This particular template is limited in that the code that gets executed based on the response can't be changed at runtime (at least not without self-modifying code.)
wait_for_key_input:
call &BB06 ;bios call, waits until key is pressed, returns key's ASCII code into A
and %11011111 ;converts to upper case
cp 'Y'
jp z,User_Chose_Yes
cp 'N'
jp z,User_Chose_No
jp wait_for_key_input
User_Chose_Yes:
;your code for what happens when the user types "Y" goes here
ret
User_Chose_No:
;your code for what happens when the user types "N" goes here
ret
- Programming Tasks
- Solutions by Programming Task
- Simple
- 8080 Assembly
- 8086 Assembly
- 8th
- Action!
- Ada
- AutoHotkey
- AWK
- Axe
- BASIC
- Applesoft BASIC
- BASIC256
- QBasic
- BBC BASIC
- Commodore BASIC
- GW-BASIC
- GW-BASIC variant
- IS-BASIC
- Locomotive Basic
- True BASIC
- SmallBASIC
- Yabasic
- ZX Spectrum Basic
- Batch File
- C
- C sharp
- C++
- Clojure
- Jline
- Common Lisp
- LispWorks
- Ncurses
- D
- Delphi
- System.Console
- EGL
- Elm
- ERRE
- Euphoria
- F Sharp
- Forth
- Fortran
- FreeBASIC
- FutureBasic
- GlovePIE
- Go
- Curses
- Haskell
- Icon
- Unicon
- Inform 7
- Java
- JavaScript
- Julia
- Kotlin
- Liberty BASIC
- LiveCode
- Logo
- M2000 Interpreter
- Mathematica
- Wolfram Language
- Microsoft Small Basic
- MiniScript
- MUMPS
- NetRexx
- Nim
- Gintro
- NS-HUBASIC
- OCaml
- Oforth
- OpenEdge/Progress
- PARI/GP
- Pascal
- CRT
- Perl
- Phix
- Phix/basics
- PicoLisp
- PL/I
- PowerShell
- PureBasic
- Python
- QB64
- QUACKASM
- Racket
- Raku
- REXX
- Ring
- RPL
- Ruby
- Run BASIC
- Rust
- Scala
- Seed7
- Sidef
- SparForte
- Tcl
- TXR
- UNIX Shell
- VB-DOS
- Vedit macro language
- V (Vlang)
- Wee Basic
- Wren
- XPL0
- Z80 Assembly
- GUISS/Omit
- Keyboard input