Keyboard input/Obtain a Y or N response: Difference between revisions

Content added Content deleted
m (syntax highlighting fixup automation)
Line 15: Line 15:
This program uses CP/M to read the keyboard.
This program uses CP/M to read the keyboard.


<lang 8080asm>rawio: equ 6 ; Raw console input
<syntaxhighlight lang="8080asm">rawio: equ 6 ; Raw console input
puts: equ 9 ; String output
puts: equ 9 ; String output
bdos: equ 5 ; CP/M entry point
bdos: equ 5 ; CP/M entry point
Line 50: Line 50:
jmp bdos ; Otherwise, print 'No'
jmp bdos ; Otherwise, print 'No'
yes: db 'Yes$'
yes: db 'Yes$'
no: db 'No$'</lang>
no: db 'No$'</syntaxhighlight>




Line 56: Line 56:
{{works with|MS-DOS}}
{{works with|MS-DOS}}
;Assembled using UASM v2.49
;Assembled using UASM v2.49
<lang asm> .model small
<syntaxhighlight lang="asm"> .model small
.stack 1024
.stack 1024
Line 162: Line 162:


end start</lang>
end start</syntaxhighlight>


=={{header|8th}}==
=={{header|8th}}==
<lang forth>
<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 176: 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!}}==
=={{header|Action!}}==
<lang Action!>PROC MAIN()
<syntaxhighlight lang="action!">PROC MAIN()
Byte Key=764
Byte Key=764


Line 194: Line 194:
If Key=35 then Printe("No ") Fi
If Key=35 then Printe("No ") Fi


RETURN</lang>
RETURN</syntaxhighlight>


=={{header|Ada}}==
=={{header|Ada}}==


<lang Ada> function Yes_Or_No (Prompt : String := "Your answer (Y/N): ") return Boolean is
<syntaxhighlight lang="ada"> function Yes_Or_No (Prompt : String := "Your answer (Y/N): ") return Boolean is
Answer : Character;
Answer : Character;
begin
begin
Line 210: Line 210:
end case;
end case;
end loop;
end loop;
end Yes_Or_No;</lang>
end Yes_Or_No;</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>Loop, {
<syntaxhighlight lang="autohotkey">Loop, {
Input, Key, L1
Input, Key, L1
if (Key = "n" || Key = "y")
if (Key = "n" || Key = "y")
Line 219: Line 219:
}
}
MsgBox, % "The response was """ Key """."
MsgBox, % "The response was """ Key """."
ExitApp</lang>
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 240: Line 240:
return(rec)
return(rec)
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 249: 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.
<lang axe>While getKey(0)
<syntaxhighlight lang="axe">While getKey(0)
End
End


Line 260: Line 260:
Return
Return
End
End
End</lang>
End</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
Line 266: Line 266:
==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===


<lang applesoftbasic>10 LET C = PEEK (49168): REM CLEAR KEYBOARD
<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}}===
==={{header|BASIC256}}===
<lang freebasic>print "Do you want to continue y/n : ";
<syntaxhighlight lang="freebasic">print "Do you want to continue y/n : ";
do
do
KBD$ = key
KBD$ = key
Line 285: Line 285:
else
else
print "OK, finishing"
print "OK, finishing"
end if</lang>
end if</syntaxhighlight>


==={{header|QBasic}}===
==={{header|QBasic}}===
<lang QBasic>PRINT "Press Y or N to continue."
<syntaxhighlight lang="qbasic">PRINT "Press Y or N to continue."
DO
DO
KBD$ = ""
KBD$ = ""
Line 296: Line 296:
IF KBD$ <> "Y" AND KBD$ <> "N" THEN BEEP
IF KBD$ <> "Y" AND KBD$ <> "N" THEN BEEP
LOOP UNTIL KBD$ = "Y" OR KBD$ = "N"
LOOP UNTIL KBD$ = "Y" OR KBD$ = "N"
PRINT "The response was "; KBD$</lang>
PRINT "The response was "; KBD$</syntaxhighlight>


==={{header|BBC BASIC}}===
==={{header|BBC BASIC}}===
<lang bbcbasic> REPEAT UNTIL INKEY$(0) = ""
<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$</lang>
PRINT "The response was " key$</syntaxhighlight>


==={{header|Commodore BASIC}}===
==={{header|Commodore BASIC}}===
<lang basic>10 PRINT "PRESS Y OR N TO CONTINUE:";
<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$</lang>
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 319: Line 319:
==={{header|GW-BASIC}}===
==={{header|GW-BASIC}}===
{{works with|QBasic}}
{{works with|QBasic}}
<lang gwbasic>10 CLS: PRINT "Press Y or N to continue."
<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 328: Line 328:
80 WEND
80 WEND
90 PRINT "The response was "; T$
90 PRINT "The response was "; T$
</syntaxhighlight>
</lang>


===={{header|GW-BASIC variant}}====
===={{header|GW-BASIC variant}}====
<lang gwbasic>10 DEF FNUP$(C$)=CHR$(ASC(C$)-32*(ASC(C$)>96)*(ASC(C$)<123))
<syntaxhighlight 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 337: 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$</lang>
70 PRINT "The response was: "; T$</syntaxhighlight>


==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 GET K$ ! Flush the keyboard buffer
<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$</lang>
150 PRINT "The response was ";K$</syntaxhighlight>


==={{header|Locomotive Basic}}===
==={{header|Locomotive Basic}}===
<lang locobasic>10 CLEAR INPUT
<syntaxhighlight 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 355: 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</lang>
80 GOTO 30</syntaxhighlight>


==={{header|Yabasic}}===
==={{header|Yabasic}}===
<lang yabasic>clear screen
<syntaxhighlight lang="yabasic">clear screen


print "Do you want to continue y/n : ";
print "Do you want to continue y/n : ";
Line 371: Line 371:
else
else
print "OK, finishing"
print "OK, finishing"
end if</lang>
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>".


<lang qbasic>10 IF INKEY$<>"" THEN GO TO 10: REM flush the keyboard buffer
<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$</lang>
50 PRINT "The response was "; k$</syntaxhighlight>


=={{header|Batch File}}==
=={{header|Batch File}}==
<lang dos>
<syntaxhighlight lang="dos">
@echo off
@echo off
choice
choice
Line 389: Line 389:
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 456: Line 456:


return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp}}==
=={{header|C sharp}}==


<lang c sharp>using System;
<syntaxhighlight lang="c sharp">using System;


namespace Y_or_N
namespace Y_or_N
Line 494: Line 494:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
Windows specific
Windows specific
<lang cpp>#include <conio.h>
<syntaxhighlight lang="cpp">#include <conio.h>
#include <iostream>
#include <iostream>


Line 523: Line 523:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
Line 533: Line 533:




<lang clojure>
<syntaxhighlight lang="clojure">
(ns yprompt.core
(ns yprompt.core
(:import jline.Terminal)
(:import jline.Terminal)
Line 551: Line 551:
(defn -main [& args]
(defn -main [& args]
(prompt))
(prompt))
</syntaxhighlight>
</lang>


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
Line 559: Line 559:
Version 1:
Version 1:


<lang lisp>
<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:


<lang lisp>
<syntaxhighlight lang="lisp">
(defun y-or-n ()
(defun y-or-n ()
(clear-input *standard-input*)
(clear-input *standard-input*)
Line 575: Line 575:
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 587: Line 587:
Version 3:
Version 3:


<lang lisp>
<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 596: Line 596:
((#\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}}==
<lang d>import std.stdio: stdout, write, writefln;
<syntaxhighlight lang="d">import std.stdio: stdout, write, writefln;


extern (C) nothrow {
extern (C) nothrow {
Line 625: Line 625:
writefln("\nResponse: %c", cast(char)c);
writefln("\nResponse: %c", cast(char)c);
_STD_conio();
_STD_conio();
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>Enter Y or N: abcN
<pre>Enter Y or N: abcN
Line 631: Line 631:
=={{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 666: Line 666:
end;
end;
Readln;
Readln;
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>Press Y ou N
<pre>Press Y ou N
Line 674: Line 674:
{{Works with|EDT}}
{{Works with|EDT}}
{{Works with|RBD}}
{{Works with|RBD}}
<lang EGL>handler YesOrNoHandler type RUIhandler{initialUI =[ui], onConstructionFunction = start}
<syntaxhighlight lang="egl">handler YesOrNoHandler type RUIhandler{initialUI =[ui], onConstructionFunction = start}


ui Div { };
ui Div { };
Line 698: Line 698:
end
end
end</lang>
end</syntaxhighlight>


=={{header|Elm}}==
=={{header|Elm}}==
<lang Elm>import Char
<syntaxhighlight lang="elm">import Char
import Graphics.Element exposing (Element, empty, show)
import Graphics.Element exposing (Element, empty, show)
import Keyboard
import Keyboard
Line 728: Line 728:
main : Signal Element
main : Signal Element
main =
main =
Signal.map view Keyboard.presses</lang>
Signal.map view Keyboard.presses</syntaxhighlight>


=={{header|ERRE}}==
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
!$KEY
!$KEY
................
................
Line 754: Line 754:
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}}==
<lang Euphoria>integer key
<syntaxhighlight lang="euphoria">integer key


puts(1,"Your answer? (Y/N)\n")
puts(1,"Your answer? (Y/N)\n")
Line 771: Line 771:
end while
end while


printf(1,"Your response was %s\n",key)</lang>
printf(1,"Your response was %s\n",key)</syntaxhighlight>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>open System
<syntaxhighlight lang="fsharp">open System


let rec yorn () =
let rec yorn () =
Line 786: Line 786:
| _ -> yorn()
| _ -> yorn()


printfn "\nYour choice: %c" (yorn())</lang>
printfn "\nYour choice: %c" (yorn())</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
<lang Forth>: flush ( -- ) \ discard pending input
<syntaxhighlight lang="forth">: flush ( -- ) \ discard pending input
begin key? while key drop repeat ;
begin key? while key drop repeat ;


Line 818: Line 818:
[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 ;</lang>
endcase again ;</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 824: Line 824:


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 888: Line 888:
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}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


While InKey <> "" : Wend '' flush keyboard buffer
While InKey <> "" : Wend '' flush keyboard buffer
Line 909: Line 909:
End If
End If


Sleep</lang>
Sleep</syntaxhighlight>


Sample input/output:
Sample input/output:
Line 920: Line 920:


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
<lang futurebasic>void local fn DoDialog( ev as long )
<syntaxhighlight lang="futurebasic">void local fn DoDialog( ev as long )
CFStringRef key
CFStringRef key
Line 940: Line 940:
on dialog fn DoDialog
on dialog fn DoDialog


HandleEvents</lang>
HandleEvents</syntaxhighlight>


=={{header|GlovePIE}}==
=={{header|GlovePIE}}==
<lang glovepie>if var.end=0 then
<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 954: Line 954:
var.end=1
var.end=1
debug="You pressed the N key."
debug="You pressed the N key."
endif</lang>
endif</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==
{{libheader|Curses}}
{{libheader|Curses}}
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 987: Line 987:
s.Refresh()
s.Refresh()
s.GetChar()
s.GetChar()
}</lang>
}</syntaxhighlight>
::<lang go>package main
::<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 1,014: Line 1,014:
fmt.Println("no")
fmt.Println("no")
}
}
}</lang>
}</syntaxhighlight>


=={{header|GW-BASIC}}==
=={{header|GW-BASIC}}==
<lang qbasic>10 IF INKEY$<>"" THEN GOTO 10: REM flush the keyboard buffer
<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$</lang>
50 PRINT "The response was "; k$</syntaxhighlight>


=={{header|Haskell}}==
=={{header|Haskell}}==
Line 1,027: Line 1,027:
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.


<lang haskell>import System.IO
<syntaxhighlight lang="haskell">import System.IO


hFlushInput :: Handle -> IO ()
hFlushInput :: Handle -> IO ()
Line 1,055: Line 1,055:
hFlushInput stdin
hFlushInput stdin
answer <- yorn
answer <- yorn
putStrLn [answer]</lang>
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>.
<lang unicon>procedure main()
<syntaxhighlight lang="unicon">procedure main()
write("Response was ",getResponse("OK? (Y or N): "))
write("Response was ",getResponse("OK? (Y or N): "))
end
end
Line 1,069: Line 1,069:
repeat if map(answer := getch()) == ("y"|"n") then break
repeat if map(answer := getch()) == ("y"|"n") then break
return answer
return answer
end</lang>
end</syntaxhighlight>


=={{header|Inform 7}}==
=={{header|Inform 7}}==
Line 1,076: Line 1,076:


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:
<lang inform7>Qwantz is a room.
<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.</lang>
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:
<lang inform7>To decide whether player consents: (- (YesOrNoKey()) -).
<syntaxhighlight lang="inform7">To decide whether player consents: (- (YesOrNoKey()) -).


Include (-
Include (-
Line 1,090: Line 1,090:
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';
]; -).</lang>
]; -).</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 1,096: Line 1,096:
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.


<lang javascript>const readline = require('readline');
<syntaxhighlight lang="javascript">const readline = require('readline');
readline.emitKeypressEvents(process.stdin);
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.setRawMode(true);
Line 1,125: Line 1,125:


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.


<lang javascript>var keypress = require('keypress');
<syntaxhighlight lang="javascript">var keypress = require('keypress');


keypress(process.stdin);
keypress(process.stdin);
Line 1,141: Line 1,141:


process.stdin.setRawMode(true);
process.stdin.setRawMode(true);
process.stdin.resume();</lang>
process.stdin.resume();</syntaxhighlight>


Using DOM events.
Using DOM events.


<lang javascript>document.body.addEventListener('keyup', function (e) {
<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);</lang>
}, false);</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
Uses the Gtk library.
Uses the Gtk library.
<lang julia>using Gtk.ShortNames
<syntaxhighlight lang="julia">using Gtk.ShortNames
function keypresswindow()
function keypresswindow()
Line 1,178: Line 1,178:
keypresswindow()
keypresswindow()
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


import java.awt.event.KeyAdapter
import java.awt.event.KeyAdapter
Line 1,220: Line 1,220:
f.isVisible = true
f.isVisible = true
}
}
}</lang>
}</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,249: Line 1,249:
end
end
end sub
end sub
</lang>
</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==
Line 1,255: Line 1,255:


In the text field, put the following in its code
In the text field, put the following in its code
<lang LiveCode>on KeyDown k
<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,262: Line 1,262:
end if
end if
put empty into me
put empty into me
end KeyDown</lang>
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}}==
<lang logo>to yorn
<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,275: Line 1,275:
print :yorn
print :yorn
output :yorn
output :yorn
end</lang>
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,291: Line 1,291:
}
}
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,315: Line 1,315:
}
}
Checkit
Checkit
</syntaxhighlight>
</lang>


===Using Thread to read/write Keyboard buffer===
===Using Thread to read/write Keyboard buffer===
Line 1,324: Line 1,324:
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,357: Line 1,357:
}
}
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,381: Line 1,381:
}
}
UseUIForm
UseUIForm
</syntaxhighlight>
</lang>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>CreateDialog[TextCell["Yes or no?[Y/N]"],
<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[]
]}];</lang>
]}];</syntaxhighlight>


=={{header|Microsoft Small Basic}}==
=={{header|Microsoft Small Basic}}==
Line 1,395: Line 1,395:
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.
<lang vb>'From:
<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,403: Line 1,403:
Sub OnKeyDown
Sub OnKeyDown
TextWindow.WriteLine(GraphicsWindow.LastKey)
TextWindow.WriteLine(GraphicsWindow.LastKey)
EndSub</lang>
EndSub</syntaxhighlight>


=={{header|MiniScript}}==
=={{header|MiniScript}}==
Line 1,409: Line 1,409:
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.


<lang MiniScript>// flush the keyboard
<syntaxhighlight lang="miniscript">// flush the keyboard
while key.available
while key.available
key.get
key.get
Line 1,420: Line 1,420:
k = key.get.upper
k = key.get.upper
end while
end while
print "You pressed: " + k</lang>
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.
<lang MUMPS>for read !,"Enter Y or N to continue: ",input quit:input?1(1"Y",1"y",1"N",1"n")</lang>
<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,434: Line 1,434:


=={{header|NetRexx}}==
=={{header|NetRexx}}==
<lang netrexx>/* 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,444: Line 1,444:
when c='N' Then Say 'NO'
when c='N' Then Say 'NO'
otherwise Say 'Undecided'
otherwise Say 'Undecided'
End </lang>
End </syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
{{libheader|gintro}}
{{libheader|gintro}}
Using "gintro" bindings to Gtk3.
Using "gintro" bindings to Gtk3.
<lang Nim>import strformat
<syntaxhighlight lang="nim">import strformat
import gintro/[glib, gobject, gtk, gio]
import gintro/[glib, gobject, gtk, gio]
import gintro/gdk except Window
import gintro/gdk except Window
Line 1,489: Line 1,489:
let app = newApplication(Application, "Rosetta.YNResponse")
let app = newApplication(Application, "Rosetta.YNResponse")
discard app.connect("activate", activate)
discard app.connect("activate", activate)
discard app.run()</lang>
discard app.run()</syntaxhighlight>


=={{header|NS-HUBASIC}}==
=={{header|NS-HUBASIC}}==
<lang NS-HUBASIC>10 PRINT "PRESS Y OR N TO CONTINUE."
<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$;"."</lang>
30 PRINT "THE RESPONSE WAS ";INKEY$;"."</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
Line 1,507: Line 1,507:
Here we define some helper functions that we'll use:
Here we define some helper functions that we'll use:


<lang OCaml>let attrs = Unix.(tcgetattr stdin)
<syntaxhighlight lang="ocaml">let attrs = Unix.(tcgetattr stdin)
let buf = Bytes.create 1
let buf = Bytes.create 1


Line 1,516: Line 1,516:
let getchar () =
let getchar () =
let len = Unix.(read stdin) buf 0 1 in
let len = Unix.(read stdin) buf 0 1 in
if len = 0 then raise End_of_file else Bytes.get buf 0</lang>
if len = 0 then raise End_of_file else Bytes.get buf 0</syntaxhighlight>


Now the main program:
Now the main program:
<lang OCaml>let rec loop () =
<syntaxhighlight lang="ocaml">let rec loop () =
print_string "Prompt? [Y/N]: "; flush stdout;
print_string "Prompt? [Y/N]: "; flush stdout;
loop
loop
Line 1,528: Line 1,528:
| _ -> ": Invalid."
| _ -> ": Invalid."


let _ = try loop @@ prompt true with Exit | End_of_file -> prompt false</lang>
let _ = try loop @@ prompt true with Exit | End_of_file -> prompt false</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>import: console
<syntaxhighlight lang="oforth">import: console


: YorN
: YorN
Line 1,541: Line 1,541:
c 'Y' <> c 'N' <> and
c 'Y' <> c 'N' <> and
]
]
c ;</lang>
c ;</syntaxhighlight>


=={{header|OpenEdge/Progress}}==
=={{header|OpenEdge/Progress}}==
<lang progress>DEF VAR lanswer AS LOGICAL INITIAL ?.
<syntaxhighlight lang="progress">DEF VAR lanswer AS LOGICAL INITIAL ?.


DO WHILE lanswer = ?:
DO WHILE lanswer = ?:
Line 1,552: Line 1,552:
END.
END.


MESSAGE lanswer VIEW-AS ALERT-BOX.</lang>
MESSAGE lanswer VIEW-AS ALERT-BOX.</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Line 1,561: Line 1,561:
{{works with|Free_Pascal}}
{{works with|Free_Pascal}}
{{libheader|CRT}}
{{libheader|CRT}}
<lang pascal>Program ObtainYN;
<syntaxhighlight lang="pascal">Program ObtainYN;


uses
uses
Line 1,576: Line 1,576:
writeln;
writeln;
writeln ('Your answer was: ', key);
writeln ('Your answer was: ', key);
end.</lang>
end.</syntaxhighlight>
Output:
Output:
<pre>% ./ObtainYN
<pre>% ./ObtainYN
Line 1,584: Line 1,584:


=={{header|Perl}}==
=={{header|Perl}}==
<lang perl>use Term::ReadKey;
<syntaxhighlight lang="perl">use Term::ReadKey;


ReadMode 4; # change to raw input mode
ReadMode 4; # change to raw input mode
Line 1,600: Line 1,600:


print "\nYou typed: $key\n";
print "\nYou typed: $key\n";
</syntaxhighlight>
</lang>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
For 1970s-style character console (/beginner) applications:
For 1970s-style character console (/beginner) applications:
<!--<lang Phix>-->
<!--<syntaxhighlight lang="phix">-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">key</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">key</span>
Line 1,618: Line 1,618:
<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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
For GUI (graphical user interface) applications, use something more like this:
For GUI (graphical user interface) applications, use something more like this:
<!--<lang Phix>-->
<!--<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;">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;">'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>
Line 1,628: Line 1,628:
<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>
<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>
<!--</lang>-->
<!--</syntaxhighlight>-->
See [[Keyboard_macros#Phix]] or [[Conway%27s_Game_of_Life#Phix]] for a more complete example
See [[Keyboard_macros#Phix]] or [[Conway%27s_Game_of_Life#Phix]] for a more complete example


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de yesno ()
<syntaxhighlight lang="picolisp">(de yesno ()
(loop
(loop
(NIL (uppc (key)))
(NIL (uppc (key)))
(T (= "Y" @) T)
(T (= "Y" @) T)
(T (= "N" @)) ) )</lang>
(T (= "N" @)) ) )</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli> yn: Proc Options(main):
<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,653: Line 1,653:
Put Skip List('Undecided?');
Put Skip List('Undecided?');
End;
End;
End;</lang>
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,665: Line 1,665:


$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,683: Line 1,683:
=={{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.
<lang PureBasic>PrintN("Press Y or N to continue")
<syntaxhighlight lang="purebasic">PrintN("Press Y or N to continue")


Repeat
Repeat
Line 1,694: Line 1,694:
Delay(1)
Delay(1)
Until Key$="Y" Or Key$="N"
Until Key$="Y" Or Key$="N"
PrintN("The response was "+Key$)</lang>
PrintN("The response was "+Key$)</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
<lang python>#!/usr/bin/env python
<syntaxhighlight lang="python">#!/usr/bin/env python


try:
try:
Line 1,718: Line 1,718:
if char.lower() in ("y", "n"):
if char.lower() in ("y", "n"):
print char
print char
break</lang>
break</syntaxhighlight>
----
----
<lang python>#!/usr/bin/env python
<syntaxhighlight lang="python">#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
from curses import wrapper
from curses import wrapper
Line 1,747: Line 1,747:
if __name__ == "__main__":
if __name__ == "__main__":
#
#
wrapper(main)</lang>
wrapper(main)</syntaxhighlight>


=={{header|QB64}}==
=={{header|QB64}}==
''CBTJD'': 2020/03/15
''CBTJD'': 2020/03/15
<lang qbasic>WHILE INKEY$ <> "": WEND ' Flushes keyboard buffer.
<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.</lang>
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).
<lang quackasm>
<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,774: Line 1,774:
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,798: Line 1,798:
[else (loop)]))
[else (loop)]))
(stty tty-settings)
(stty tty-settings)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
<lang perl6>my $TTY = open("/dev/tty");
<syntaxhighlight lang="raku" line>my $TTY = open("/dev/tty");


sub prompt-char($prompt) {
sub prompt-char($prompt) {
Line 1,812: Line 1,812:
}
}


say so prompt-char("Y or N? ") ~~ /:i y/;</lang>
say so prompt-char("Y or N? ") ~~ /:i y/;</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
Line 1,828: Line 1,828:
<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 &nbsp; (see the other versions below).
<br>they are pressed &nbsp; (see the other versions below).
<lang rexx>/*REXX program tests for a Y or N key when entered from keyboard after a prompt.*/
<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,839: Line 1,839:
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. */</lang>
/*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.
<lang rexx>/*REXX program tests for a Y or N key when entered from keyboard after a prompt.*/
<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,850: Line 1,850:
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. */</lang>
/*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.
<lang rexx>/*REXX program tests for a Y or N key when entered from keyboard after a prompt.*/
<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,861: Line 1,861:
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. */</lang>
/*stick a fork in it, we're all done. */</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
while true
while true
give c
give c
Line 1,871: Line 1,871:
else see "Try again!" + nl ok
else see "Try again!" + nl ok
end
end
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<syntaxhighlight lang="ruby">
<lang Ruby>
def yesno
def yesno
begin
begin
Line 1,890: Line 1,890:
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,903: Line 1,903:
end
end
end
end
</syntaxhighlight>
</lang>


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>[loop] cls ' Clear screen
<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,914: Line 1,914:
[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}}
<lang rust>//cargo-deps: ncurses
<syntaxhighlight lang="rust">//cargo-deps: ncurses


extern crate ncurses;
extern crate ncurses;
Line 1,938: Line 1,938:
refresh();
refresh();
endwin();
endwin();
}</lang>
}</syntaxhighlight>


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala> println(if (scala.io.StdIn.readBoolean) "Yes typed." else "Something else.")</lang>
<syntaxhighlight lang="scala"> println(if (scala.io.StdIn.readBoolean) "Yes typed." else "Something else.")</syntaxhighlight>


----
----
<lang scala>
<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>
----
----
<lang scala>
<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,956: Line 1,956:
//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}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "keybd.s7i";
include "keybd.s7i";


Line 1,981: Line 1,981:
begin
begin
writeln(yesOrNo("Press Y or N to continue "));
writeln(yesOrNo("Press Y or N to continue "));
end func;</lang>
end func;</syntaxhighlight>


=={{header|Sidef}}==
=={{header|Sidef}}==
{{trans|Perl}}
{{trans|Perl}}
<lang ruby>func prompt_yn {
<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 2,001: Line 2,001:


var key = prompt_yn();
var key = prompt_yn();
say "You typed: #{key}";</lang>
say "You typed: #{key}";</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,015: Line 2,015:
Using the console (expects U*Xish <tt>stty</tt>)
Using the console (expects U*Xish <tt>stty</tt>)


<lang tcl>proc yesno {{message "Press Y or N to continue"}} {
<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 2,031: Line 2,031:
}
}


set yn [yesno "Do you like programming (Y/N)"]</lang>
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):


<lang tcl>
<syntaxhighlight lang="tcl">
proc yesno {message} {
proc yesno {message} {
toplevel .msg
toplevel .msg
Line 2,048: Line 2,048:
yesno "Do you like programming?"
yesno "Do you like programming?"


</syntaxhighlight>
</lang>


=={{header|TXR}}==
=={{header|TXR}}==
Line 2,054: Line 2,054:
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].


<lang txrlisp>(with-resources ((tio-orig (tcgetattr) (tcsetattr tio-orig)))
<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))))))))</lang>
((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 2,065: Line 2,065:
<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:


<lang txrlisp>(defmeth termios go-raw (tio)
<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 2,074: Line 2,074:
tio.(set-cflags cs8)
tio.(set-cflags cs8)
(set tio.[cc vmin] 1)
(set tio.[cc vmin] 1)
(set tio.[cc vtime] 0))</lang>
(set tio.[cc vtime] 0))</syntaxhighlight>


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
{{works with|Bourne Again SHell}}
<lang bash>getkey() {
<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 2,101: Line 2,101:
[Nn]) echo >&2 N; return 1;;
[Nn]) echo >&2 N; return 1;;
esac
esac
}</lang>
}</syntaxhighlight>


Cleaner version using bash built-ins
Cleaner version using bash built-ins


<lang sh>#!/bin/bash
<syntaxhighlight lang="sh">#!/bin/bash


yorn() {
yorn() {
Line 2,122: Line 2,122:
}
}


yorn</lang>
yorn</syntaxhighlight>


=={{header|VB-DOS}}==
=={{header|VB-DOS}}==
<lang vb>OPTION EXPLICIT
<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 2,131: Line 2,131:
IF T = 6 THEN PRINT "yes"; ELSE PRINT "no";
IF T = 6 THEN PRINT "yes"; ELSE PRINT "no";
PRINT "."
PRINT "."
END</lang>
END</syntaxhighlight>


=={{header|Vedit macro language}}==
=={{header|Vedit macro language}}==
<lang vedit>Key_Purge() // flush keyboard buffer
<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') </lang>
} while (#1 != 'Y' && #1 != 'N') </syntaxhighlight>


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang vlang>import term.ui as tui
<syntaxhighlight lang="vlang">import term.ui as tui


struct App {
struct App {
Line 2,190: Line 2,190:
println('V term.input event viewer (type `y`, `Y`, `n`, or `N` to exit)\n\n')
println('V term.input event viewer (type `y`, `Y`, `n`, or `N` to exit)\n\n')
app.tui.run()?
app.tui.run()?
}</lang>
}</syntaxhighlight>


=={{header|Wee Basic}}==
=={{header|Wee Basic}}==
<lang Wee Basic>print 1 "Enter Y for yes, or N for no. (not case sensitive)"
<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 2,213: Line 2,213:
wend
wend
print 1 "You entered"+response$
print 1 "You entered"+response$
end</lang>
end</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>import "io" for Stdin, Stdout
<syntaxhighlight lang="ecmascript">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 2,228: Line 2,228:
System.print(yn)
System.print(yn)


Stdin.isRaw = false</lang>
Stdin.isRaw = false</syntaxhighlight>


{{out}}
{{out}}
Line 2,238: Line 2,238:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<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 2,246: Line 2,246:
other ChOut(0, 7\bel\);
other ChOut(0, 7\bel\);
CrLf(0);
CrLf(0);
]</lang>
]</syntaxhighlight>
=={{header|Z80 Assembly}}==
=={{header|Z80 Assembly}}==
{{works with|Amstrad CPC}}
{{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.)
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.)
<lang z80>wait_for_key_input:
<syntaxhighlight lang="z80">wait_for_key_input:
call &BB06 ;bios call, waits until key is pressed, returns key's ASCII code into A
call &BB06 ;bios call, waits until key is pressed, returns key's ASCII code into A
and %11011111 ;converts to upper case
and %11011111 ;converts to upper case
Line 2,265: Line 2,265:
User_Chose_No:
User_Chose_No:
;your code for what happens when the user types "N" goes here
;your code for what happens when the user types "N" goes here
ret</lang>
ret</syntaxhighlight>
{{omit from|GUISS}}
{{omit from|GUISS}}