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

m
Use inputReady instead of the deprecated function keypress
No edit summary
m (Use inputReady instead of the deprecated function keypress)
 
(11 intermediate revisions by 8 users not shown)
Line 15:
This program uses CP/M to read the keyboard.
 
<langsyntaxhighlight lang="8080asm">rawio: equ 6 ; Raw console input
puts: equ 9 ; String output
bdos: equ 5 ; CP/M entry point
Line 50:
jmp bdos ; Otherwise, print 'No'
yes: db 'Yes$'
no: db 'No$'</langsyntaxhighlight>
 
 
Line 56:
{{works with|MS-DOS}}
;Assembled using UASM v2.49
<langsyntaxhighlight lang="asm"> .model small
.stack 1024
Line 162:
 
end start</langsyntaxhighlight>
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
\ get a yes or no response from the keyboard
: yes-no
Line 176:
"Yes or no? " con:print yes-no no?
cr bye
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC MAIN()
Byte Key=764
 
Line 194:
If Key=35 then Printe("No ") Fi
 
RETURN</langsyntaxhighlight>
 
=={{header|Ada}}==
 
<langsyntaxhighlight Adalang="ada"> function Yes_Or_No (Prompt : String := "Your answer (Y/N): ") return Boolean is
Answer : Character;
begin
Line 210:
end case;
end loop;
end Yes_Or_No;</langsyntaxhighlight>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">Loop, {
Input, Key, L1
if (Key = "n" || Key = "y")
Line 219:
}
MsgBox, % "The response was """ Key """."
ExitApp</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f KEYBOARD_INPUT_OBTAIN_A_Y_OR_N_RESPONSE.AWK
BEGIN {
Line 240:
return(rec)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 249:
=={{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.
<langsyntaxhighlight lang="axe">While getKey(0)
End
 
Line 260:
Return
End
End</langsyntaxhighlight>
 
=={{header|BASIC}}==
Line 266:
==={{header|Applesoft BASIC}}===
 
<langsyntaxhighlight lang="applesoftbasic">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$
</syntaxhighlight>
</lang>
 
==={{header|BASIC256}}===
<langsyntaxhighlight lang="freebasic">print "Do you want to continue y/n : ";
do
KBD$ = key
Line 285:
else
print "OK, finishing"
end if</langsyntaxhighlight>
 
==={{header|QBasic}}===
<langsyntaxhighlight QBasiclang="qbasic">PRINT "Press Y or N to continue."
DO
KBD$ = ""
Line 296:
IF KBD$ <> "Y" AND KBD$ <> "N" THEN BEEP
LOOP UNTIL KBD$ = "Y" OR KBD$ = "N"
PRINT "The response was "; KBD$</langsyntaxhighlight>
 
==={{header|BBC BASIC}}===
<langsyntaxhighlight lang="bbcbasic"> 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$</langsyntaxhighlight>
 
==={{header|Commodore BASIC}}===
<langsyntaxhighlight lang="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$</langsyntaxhighlight>
 
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:
==={{header|GW-BASIC}}===
{{works with|QBasic}}
<langsyntaxhighlight lang="gwbasic">10 CLS: PRINT "Press Y or N to continue."
20 WHILE T$<>"y" AND T$<>"Y" AND T$<>"n" AND T$<>"N"
30 T$=""
Line 328:
80 WEND
90 PRINT "The response was "; T$
</syntaxhighlight>
</lang>
 
===={{header|GW-BASIC variant}}====
<langsyntaxhighlight 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."
30 WHILE T$<>"Y" AND T$<>"N"
Line 337:
50 IF T$<>"Y" AND T$<>"N" THEN BEEP
60 WEND
70 PRINT "The response was: "; T$</langsyntaxhighlight>
 
==={{header|IS-BASIC}}===
<langsyntaxhighlight ISlang="is-BASICbasic">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$</langsyntaxhighlight>
 
==={{header|Locomotive Basic}}===
<langsyntaxhighlight lang="locobasic">10 CLEAR INPUT
20 PRINT "Press Y or N to continue"
30 a$=LOWER$(INKEY$)
Line 355:
60 IF a$="n" THEN PRINT "No":END
70 PRINT "Try again"
80 GOTO 30</langsyntaxhighlight>
 
==={{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|Yabasic}}===
<langsyntaxhighlight lang="yabasic">clear screen
 
print "Do you want to continue y/n : ";
Line 371 ⟶ 386:
else
print "OK, finishing"
end if</langsyntaxhighlight>
 
==={{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>".
 
<langsyntaxhighlight lang="qbasic">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$</langsyntaxhighlight>
 
=={{header|Batch File}}==
<langsyntaxhighlight lang="dos">
@echo off
choice
Line 389 ⟶ 404:
if errorlevel 1 echo You chose Y
>nul pause
</syntaxhighlight>
</lang>
 
=={{header|C}}==
For POSIX compliant systems (in theory that includes WinNT family).
<syntaxhighlight lang="c">
<lang C>
#include <stdio.h>
#include <termios.h>
Line 456 ⟶ 471:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
 
<langsyntaxhighlight lang="c sharp">using System;
 
namespace Y_or_N
Line 494 ⟶ 509:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Windows specific
<langsyntaxhighlight lang="cpp">#include <conio.h>
#include <iostream>
 
Line 523 ⟶ 538:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
Line 533 ⟶ 548:
 
 
<langsyntaxhighlight lang="clojure">
(ns yprompt.core
(:import jline.Terminal)
Line 551 ⟶ 566:
(defn -main [& args]
(prompt))
</syntaxhighlight>
</lang>
 
=={{header|Common Lisp}}==
Line 559 ⟶ 574:
Version 1:
 
<langsyntaxhighlight lang="lisp">
(defun rosetta-y-or-n ()
(clear-input *query-io*)
(y-or-n-p))
</syntaxhighlight>
</lang>
 
Version 2:
 
<langsyntaxhighlight lang="lisp">
(defun y-or-n ()
(clear-input *standard-input*)
Line 575 ⟶ 590:
when q do (format t "~%Need Y or N~%")
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.
Line 587 ⟶ 602:
Version 3:
 
<langsyntaxhighlight lang="lisp">
(defun y-or-no ()
(with-screen (scr :input-buffering nil :input-blocking t)
Line 596 ⟶ 611:
((#\Y #\y) (return-from event-case t))
((#\N #\n) (return-from event-case nil)))))
</syntaxhighlight>
</lang>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio: stdout, write, writefln;
 
extern (C) nothrow {
Line 625 ⟶ 640:
writefln("\nResponse: %c", cast(char)c);
_STD_conio();
}</langsyntaxhighlight>
{{out}}
<pre>Enter Y or N: abcN
Line 631 ⟶ 646:
=={{header|Delphi}}==
{{libheader| System.Console}} Thanks for JensBorrisholt [https://github.com/JensBorrisholt/DelphiConsole].
<syntaxhighlight lang="delphi">
<lang Delphi>
program Obtain_a_Y_or_N_response;
 
Line 666 ⟶ 681:
end;
Readln;
end.</langsyntaxhighlight>
{{out}}
<pre>Press Y ou N
Line 674 ⟶ 689:
{{Works with|EDT}}
{{Works with|RBD}}
<langsyntaxhighlight EGLlang="egl">handler YesOrNoHandler type RUIhandler{initialUI =[ui], onConstructionFunction = start}
 
ui Div { };
Line 698 ⟶ 713:
end
end</langsyntaxhighlight>
 
=={{header|Elm}}==
<langsyntaxhighlight Elmlang="elm">import Char
import Graphics.Element exposing (Element, empty, show)
import Keyboard
Line 728 ⟶ 743:
main : Signal Element
main =
Signal.map view Keyboard.presses</langsyntaxhighlight>
 
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
<lang ERRE>
!$KEY
................
Line 754 ⟶ 769:
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.
 
=={{header|Euphoria}}==
<langsyntaxhighlight Euphorialang="euphoria">integer key
 
puts(1,"Your answer? (Y/N)\n")
Line 771 ⟶ 786:
end while
 
printf(1,"Your response was %s\n",key)</langsyntaxhighlight>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
 
let rec yorn () =
Line 786 ⟶ 801:
| _ -> yorn()
 
printfn "\nYour choice: %c" (yorn())</langsyntaxhighlight>
 
=={{header|Forth}}==
<langsyntaxhighlight Forthlang="forth">: flush ( -- ) \ discard pending input
begin key? while key drop repeat ;
 
Line 818 ⟶ 833:
[char] n of 2drop false exit endof
[char] N of 2drop false exit endof
endcase again ;</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 824 ⟶ 839:
 
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.
Concocted by R.N.McLean (whom God preserve), December MM.
Line 888 ⟶ 903:
RETURN !Pass the inverted word.
END !So much for naysayers.
</syntaxhighlight>
</lang>
Usage might be something like <code>IF (NAY("Keep the results")) CALL PURGE</code>
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
While InKey <> "" : Wend '' flush keyboard buffer
Line 909 ⟶ 924:
End If
 
Sleep</langsyntaxhighlight>
 
Sample input/output:
Line 920 ⟶ 935:
 
=={{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 case( evlcase(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 fn
 
subclass
window 1, @"Press \"Y\" or \"N\" keys", (0,0,550,400)
 
on dialog fn DoDialog
 
HandleEvents</syntaxhighlight>
window 1, @"Yes-No", (0,0)-(150,80), _docNoGrow
text _applFont, 14, _boldBit%
 
RunApplicationEventLoop()
</lang>
 
=={{header|GlovePIE}}==
<langsyntaxhighlight lang="glovepie">if var.end=0 then
var.end=0
debug="Press the Y key or the N key to continue:"
Line 958 ⟶ 969:
var.end=1
debug="You pressed the N key."
endif</langsyntaxhighlight>
 
=={{header|Go}}==
{{libheader|Curses}}
<langsyntaxhighlight lang="go">package main
 
import (
Line 991 ⟶ 1,002:
s.Refresh()
s.GetChar()
}</langsyntaxhighlight>
::<langsyntaxhighlight lang="go">package main
// siongui.github.io/2016/04/23/go-read-yes-no-from-console
import (
Line 1,018 ⟶ 1,029:
fmt.Println("no")
}
}</langsyntaxhighlight>
 
=={{header|GW-BASIC}}==
<langsyntaxhighlight lang="qbasic">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$</langsyntaxhighlight>
 
=={{header|Haskell}}==
Line 1,031 ⟶ 1,042:
This may not be very idiomatic; it's pretty monad-oriented, and the use of do expressions makes the whole thing feel rather imperative.
 
<langsyntaxhighlight lang="haskell">import System.IO
 
hFlushInput :: Handle -> IO ()
Line 1,059 ⟶ 1,070:
hFlushInput stdin
answer <- yorn
putStrLn [answer]</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
 
This solution works in both Icon and Unicon. It also accepts <tt>y</tt> or <tt>n</tt>.
<langsyntaxhighlight lang="unicon">procedure main()
write("Response was ",getResponse("OK? (Y or N): "))
end
Line 1,073 ⟶ 1,084:
repeat if map(answer := getch()) == ("y"|"n") then break
return answer
end</langsyntaxhighlight>
 
=={{header|Inform 7}}==
Line 1,080 ⟶ 1,091:
 
Inform 7 has a built-in function to ask the user for yes-or-no input, but it requires them to press enter afterward:
<langsyntaxhighlight lang="inform7">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.</langsyntaxhighlight>
 
To read a single key without waiting for enter, we can redefine the function by including a snippet of Inform 6 code:
<langsyntaxhighlight lang="inform7">To decide whether player consents: (- (YesOrNoKey()) -).
 
Include (-
Line 1,094 ⟶ 1,105:
do { ch = VM_KeyChar(); } until (ch == 'y' or 'Y' or 'n' or 'N');
return ch == 'y' or 'Y';
]; -).</langsyntaxhighlight>
 
=={{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}}==
Line 1,100 ⟶ 1,169:
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.
 
<langsyntaxhighlight lang="javascript">const readline = require('readline');
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
Line 1,129 ⟶ 1,198:
 
go();
</syntaxhighlight>
</lang>
 
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.
 
<langsyntaxhighlight lang="javascript">var keypress = require('keypress');
 
keypress(process.stdin);
Line 1,145 ⟶ 1,214:
 
process.stdin.setRawMode(true);
process.stdin.resume();</langsyntaxhighlight>
 
Using DOM events.
 
<langsyntaxhighlight lang="javascript">document.body.addEventListener('keyup', function (e) {
var key = String.fromCharCode(e.keyCode).toLowerCase();
if (key === 'y' || key === 'n') {
console.log('response is: ' + key);
}
}, false);</langsyntaxhighlight>
 
=={{header|Julia}}==
Uses the Gtk library.
<langsyntaxhighlight lang="julia">using Gtk.ShortNames
function keypresswindow()
Line 1,182 ⟶ 1,251:
keypresswindow()
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
import java.awt.event.KeyAdapter
Line 1,224 ⟶ 1,293:
f.isVisible = true
}
}</langsyntaxhighlight>
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
nomainwin
open "Y/N" for graphics_nsb_nf as #1
Line 1,253 ⟶ 1,322:
end
end sub
</langsyntaxhighlight>
 
=={{header|LiveCode}}==
Line 1,259 ⟶ 1,328:
 
In the text field, put the following in its code
<langsyntaxhighlight LiveCodelang="livecode">on KeyDown k
if toUpper(k) is among the items of "Y,N" then
answer "Thanks for your response"
Line 1,266 ⟶ 1,335:
end if
put empty into me
end KeyDown</langsyntaxhighlight>
 
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}}==
<langsyntaxhighlight lang="logo">to yorn
type [Press Y or N to continue: ]
local "clear
Line 1,279 ⟶ 1,348:
print :yorn
output :yorn
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
===Simple Loop using Key$===
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 {
\\ a small modification from BBC BASIC entry
Line 1,295 ⟶ 1,364:
}
Simple
</syntaxhighlight>
</lang>
 
===Use a Function to return keypress and by reference return value===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
Function GetYN$ (&Ret) {
Line 1,319 ⟶ 1,388:
}
Checkit
</syntaxhighlight>
</lang>
 
===Using Thread to read/write Keyboard buffer===
Line 1,328 ⟶ 1,397:
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 GetYN (&Ret) {
Line 1,361 ⟶ 1,430:
}
CheckisToo
</syntaxhighlight>
</lang>
 
===Using User Form (GUI)===
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module UseUIForm {
Const Y=0x59, N=0x4E, Center=2
Line 1,385 ⟶ 1,454:
}
UseUIForm
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">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[]
]}];</langsyntaxhighlight>
 
=={{header|Microsoft Small Basic}}==
Line 1,399 ⟶ 1,468:
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.
<langsyntaxhighlight lang="vb">'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
Line 1,407 ⟶ 1,476:
Sub OnKeyDown
TextWindow.WriteLine(GraphicsWindow.LastKey)
EndSub</langsyntaxhighlight>
 
=={{header|MiniScript}}==
Line 1,413 ⟶ 1,482:
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.
 
<langsyntaxhighlight MiniScriptlang="miniscript">// flush the keyboard
while key.available
key.get
Line 1,424 ⟶ 1,493:
k = key.get.upper
end while
print "You pressed: " + k</langsyntaxhighlight>
 
=={{header|MUMPS}}==
{{works with|Caché ObjectScript}}
Version from terminal shown below.
<langsyntaxhighlight MUMPSlang="mumps">for read !,"Enter Y or N to continue: ",input quit:input?1(1"Y",1"y",1"N",1"n")</langsyntaxhighlight>
 
{{out}}<pre>Enter Y or N to continue: J
Line 1,438 ⟶ 1,507:
 
=={{header|NetRexx}}==
<langsyntaxhighlight lang="netrexx">/* NetRexx */
 
options replace format comments java crossref savelog symbols binary
Line 1,448 ⟶ 1,517:
when c='N' Then Say 'NO'
otherwise Say 'Undecided'
End </langsyntaxhighlight>
 
=={{header|Nim}}==
{{libheader|gintro}}
Using "gintro" bindings to Gtk3.
<langsyntaxhighlight Nimlang="nim">import strformat
import gintro/[glib, gobject, gtk, gio]
import gintro/gdk except Window
Line 1,493 ⟶ 1,562:
let app = newApplication(Application, "Rosetta.YNResponse")
discard app.connect("activate", activate)
discard app.run()</langsyntaxhighlight>
 
=={{header|NS-HUBASIC}}==
<langsyntaxhighlight NSlang="ns-HUBASIChubasic">10 PRINT "PRESS Y OR N TO CONTINUE."
20 IF INKEY$<>"Y" AND INKEY$<>"N" THEN GOTO 20
30 PRINT "THE RESPONSE WAS ";INKEY$;"."</langsyntaxhighlight>
 
=={{header|OCaml}}==
Line 1,511 ⟶ 1,580:
Here we define some helper functions that we'll use:
 
<langsyntaxhighlight OCamllang="ocaml">let attrs = Unix.(tcgetattr stdin)
let buf = Bytes.create 1
 
Line 1,520 ⟶ 1,589:
let getchar () =
let len = Unix.(read stdin) buf 0 1 in
if len = 0 then raise End_of_file else Bytes.get buf 0</langsyntaxhighlight>
 
Now the main program:
<langsyntaxhighlight OCamllang="ocaml">let rec loop () =
print_string "Prompt? [Y/N]: "; flush stdout;
loop
Line 1,532 ⟶ 1,601:
| _ -> ": Invalid."
 
let _ = try loop @@ prompt true with Exit | End_of_file -> prompt false</langsyntaxhighlight>
 
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">import: console
 
: YorN
Line 1,545 ⟶ 1,614:
c 'Y' <> c 'N' <> and
]
c ;</langsyntaxhighlight>
 
=={{header|OpenEdge/Progress}}==
<langsyntaxhighlight lang="progress">DEF VAR lanswer AS LOGICAL INITIAL ?.
 
DO WHILE lanswer = ?:
Line 1,556 ⟶ 1,625:
END.
 
MESSAGE lanswer VIEW-AS ALERT-BOX.</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
Line 1,565 ⟶ 1,634:
{{works with|Free_Pascal}}
{{libheader|CRT}}
<langsyntaxhighlight lang="pascal">Program ObtainYN;
 
uses
Line 1,580 ⟶ 1,649:
writeln;
writeln ('Your answer was: ', key);
end.</langsyntaxhighlight>
Output:
<pre>% ./ObtainYN
Line 1,588 ⟶ 1,657:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use Term::ReadKey;
 
ReadMode 4; # change to raw input mode
Line 1,604 ⟶ 1,673:
 
print "\nYou typed: $key\n";
</syntaxhighlight>
</lang>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
For 1970s-style character console (/beginner) applications:
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">key</span>
Line 1,622 ⟶ 1,691:
<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>
<!--</langsyntaxhighlight>-->
For GUI (graphical user interface) applications, use something more like this:
<!--<langsyntaxhighlight Phixlang="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>
Line 1,632 ⟶ 1,701:
<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>
<!--</langsyntaxhighlight>-->
See [[Keyboard_macros#Phix]] or [[Conway%27s_Game_of_Life#Phix]] for a more complete example
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de yesno ()
(loop
(NIL (uppc (key)))
(T (= "Y" @) T)
(T (= "N" @)) ) )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli"> yn: Proc Options(main):
Dcl sysin stream input;
Dcl sysprint stream output;
Line 1,657 ⟶ 1,726:
Put Skip List('Undecided?');
End;
End;</langsyntaxhighlight>
 
=={{header|PowerShell}}==
This is for console use only. The ISE is geared for a different type of input.
<syntaxhighlight lang="powershell">
<lang PowerShell>
do
{
Line 1,669 ⟶ 1,738:
 
$keyPress | Format-Table -AutoSize
</syntaxhighlight>
</lang>
If the user pressed the "Y" key...
{{Out}}
Line 1,687 ⟶ 1,756:
=={{header|PureBasic}}==
Inkey() returns the character string of the key which is being pressed at the time.
<langsyntaxhighlight PureBasiclang="purebasic">PrintN("Press Y or N to continue")
 
Repeat
Line 1,698 ⟶ 1,767:
Delay(1)
Until Key$="Y" Or Key$="N"
PrintN("The response was "+Key$)</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">#!/usr/bin/env python
 
try:
Line 1,722 ⟶ 1,791:
if char.lower() in ("y", "n"):
print char
break</langsyntaxhighlight>
----
<langsyntaxhighlight lang="python">#!/usr/bin/env python
# -*- coding: utf-8 -*-
from curses import wrapper
Line 1,751 ⟶ 1,820:
if __name__ == "__main__":
#
wrapper(main)</langsyntaxhighlight>
 
=={{header|QB64}}==
''CBTJD'': 2020/03/15
<langsyntaxhighlight lang="qbasic">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.</langsyntaxhighlight>
 
=={{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).
<langsyntaxhighlight lang="quackasm">
; Stores result in cell 2; 1 if yes, 0 if no.
:YORN
Line 1,778 ⟶ 1,847:
RETURN
:YORNMSG " (Y/N)? \
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 1,802 ⟶ 1,871:
[else (loop)]))
(stty tty-settings)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" perl6line>my $TTY = open("/dev/tty");
 
sub prompt-char($prompt) {
Line 1,816 ⟶ 1,885:
}
 
say so prompt-char("Y or N? ") ~~ /:i y/;</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 1,832 ⟶ 1,901:
<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).
<langsyntaxhighlight 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*/
Line 1,843 ⟶ 1,912:
ans=space(ans, 0) /*elide all blanks. */
end /*until*/
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
 
===version 1 for PC/REXX and Personal REXX===
This version of a REXX program works with PC/REXX and Personal REXX.
<langsyntaxhighlight 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.*/
 
Line 1,854 ⟶ 1,923:
ans=inKey('wait') /*get the answer(s) from the terminal. */
end /*until*/
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
 
===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.
<langsyntaxhighlight 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.*/
 
Line 1,865 ⟶ 1,934:
ans=inKey('wait'); upper ans /*get the answer(s); and uppercase it.*/
end /*until*/
/*stick a fork in it, we're all done. */</langsyntaxhighlight>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
while true
give c
Line 1,875 ⟶ 1,944:
else see "Try again!" + nl ok
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}}==
<syntaxhighlight lang="ruby">
<lang Ruby>
def yesno
begin
Line 1,894 ⟶ 1,972:
end
end
</syntaxhighlight>
</lang>
 
Ruby provides the io/console module since version 2.0:
<syntaxhighlight lang="ruby">
<lang Ruby>
require 'io/console'
 
Line 1,907 ⟶ 1,985:
end
end
</syntaxhighlight>
</lang>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">[loop] cls ' Clear screen
html "Click Y or N" ' no other options
button #y, "Y", [Y] ' they either click [Y]
Line 1,918 ⟶ 1,996:
[Y] msg$ = "You entered [Y]es": goto [loop]
[N] msg$ = "You entered [N]o" : goto [loop]
</syntaxhighlight>
</lang>
 
=={{header|Rust}}==
{{libheader|Ncurses}}
<langsyntaxhighlight lang="rust">//cargo-deps: ncurses
 
extern crate ncurses;
Line 1,942 ⟶ 2,020:
refresh();
endwin();
}</langsyntaxhighlight>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala"> println(if (scala.io.StdIn.readBoolean) "Yes typed." else "Something else.")</langsyntaxhighlight>
 
----
<langsyntaxhighlight lang="scala">
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")}
</syntaxhighlight>
</lang>
----
<langsyntaxhighlight lang="scala">
import scala.io.{Source, BufferedSource}
val kbd_In: BufferedSource = Source.stdin
Line 1,960 ⟶ 2,038:
//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")}
</syntaxhighlight>
</lang>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "keybd.s7i";
 
Line 1,972 ⟶ 2,050:
var char: answer is ' ';
begin
while keypressedinputReady(KEYBOARD) do
ignore(getc(KEYBOARD));
end while;
Line 1,985 ⟶ 2,063:
begin
writeln(yesOrNo("Press Y or N to continue "));
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func prompt_yn {
static rk = frequire('Term::ReadKey');
rk.ReadMode(4); # change to raw input mode
Line 2,005 ⟶ 2,083:
 
var key = prompt_yn();
say "You typed: #{key}";</langsyntaxhighlight>
{{out}}
<pre>
Line 2,014 ⟶ 2,092:
You typed: Y
</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}}==
Line 2,019 ⟶ 2,133:
Using the console (expects U*Xish <tt>stty</tt>)
 
<langsyntaxhighlight lang="tcl">proc yesno {{message "Press Y or N to continue"}} {
fconfigure stdin -blocking 0
exec stty raw
Line 2,035 ⟶ 2,149:
}
 
set yn [yesno "Do you like programming (Y/N)"]</langsyntaxhighlight>
 
Without a console (answer in the global variable yn; this should work in any GUI for which there is a TCL):
 
<langsyntaxhighlight lang="tcl">
proc yesno {message} {
toplevel .msg
Line 2,052 ⟶ 2,166:
yesno "Do you like programming?"
 
</syntaxhighlight>
</lang>
 
=={{header|TXR}}==
Line 2,058 ⟶ 2,172:
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].
 
<langsyntaxhighlight lang="txrlisp">(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))))))))</langsyntaxhighlight>
 
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,069 ⟶ 2,183:
<code>go-raw</code> is defined in the TXR standard library like this:
 
<langsyntaxhighlight lang="txrlisp">(defmeth termios go-raw (tio)
tio.(clear-iflags ignbrk brkint parmrk istrip inlcr igncr icrnl ixon)
tio.(clear-oflags opost)
Line 2,078 ⟶ 2,192:
tio.(set-cflags cs8)
(set tio.[cc vmin] 1)
(set tio.[cc vtime] 0))</langsyntaxhighlight>
 
=={{header|UNIX Shell}}==
{{works with|Bourne Again SHell}}
<langsyntaxhighlight lang="bash">getkey() {
local stty="$(stty -g)"
trap "stty $stty; trap SIGINT; return 128" SIGINT
Line 2,105 ⟶ 2,219:
[Nn]) echo >&2 N; return 1;;
esac
}</langsyntaxhighlight>
 
Cleaner version using bash built-ins
 
<langsyntaxhighlight lang="sh">#!/bin/bash
 
yorn() {
Line 2,126 ⟶ 2,240:
}
 
yorn</langsyntaxhighlight>
 
=={{header|VB-DOS}}==
<langsyntaxhighlight lang="vb">OPTION EXPLICIT
DIM T AS INTEGER
T = MSGBOX("Click on yes or no", 4, "Option")
Line 2,135 ⟶ 2,249:
IF T = 6 THEN PRINT "yes"; ELSE PRINT "no";
PRINT "."
END</langsyntaxhighlight>
 
=={{header|Vedit macro language}}==
<langsyntaxhighlight lang="vedit">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') </langsyntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import term.ui as tui
 
struct App {
Line 2,194 ⟶ 2,308:
println('V term.input event viewer (type `y`, `Y`, `n`, or `N` to exit)\n\n')
app.tui.run()?
}</langsyntaxhighlight>
 
=={{header|Wee Basic}}==
<langsyntaxhighlight Weelang="wee Basicbasic">print 1 "Enter Y for yes, or N for no. (not case sensitive)"
let loop=0
let keycode=0
Line 2,217 ⟶ 2,331:
wend
print 1 "You entered"+response$
end</langsyntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">import "io" for Stdin, Stdout
 
Stdin.isRaw = true // input is neither echoed nor buffered in this mode
Line 2,232 ⟶ 2,346:
System.print(yn)
 
Stdin.isRaw = false</langsyntaxhighlight>
 
{{out}}
Line 2,242 ⟶ 2,356:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations
loop [OpenI(1); \flush any pending keystroke
case ChIn(1) of \get keystroke
Line 2,250 ⟶ 2,364:
other ChOut(0, 7\bel\);
CrLf(0);
]</langsyntaxhighlight>
=={{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.)
<langsyntaxhighlight 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
Line 2,269 ⟶ 2,383:
User_Chose_No:
;your code for what happens when the user types "N" goes here
ret</langsyntaxhighlight>
{{omit from|GUISS}}
 
28

edits