N N N N Nothing There It Is Again

Task

Keyboard input/Obtain a Y or N response
You are encouraged to solve this task according to the task description, using any language you may know.

Task

Obtain a valid Y or Northward response from the keyboard.

The keyboard should be flushed, and then that whatever outstanding cardinal-presses are removed, preventing whatever existing Y or Due north primal-press from beingness evaluated.

The response should be obtained equally soon as Y or N are pressed, and there should be no demand to press an   enter   fundamental.

Contents

  • 1 8080 Assembly
  • 2 8086 Assembly
  • 3 8th
  • 4 Activeness!
  • 5 Ada
  • six AutoHotkey
  • vii AWK
  • viii Axe
  • 9 Bones
    • 9.1 Applesoft Bones
    • 9.2 BASIC256
    • ix.iii QBasic
    • ix.4 BBC BASIC
    • ix.5 Commodore BASIC
    • nine.6 GW-Bones
      • 9.6.one GW-BASIC variant
    • 9.seven IS-Bones
    • 9.viii Locomotive Basic
    • 9.9 Yabasic
    • ix.10 ZX Spectrum Basic
  • 10 Batch File
  • 11 C
  • 12 C#
  • 13 C++
  • 14 Clojure
  • 15 Common Lisp
    • 15.1 LispWorks
    • 15.2 ncurses
  • 16 D
  • 17 Delphi
  • 18 EGL
  • xix Elm
  • 20 ERRE
  • 21 Euphoria
  • 22 F#
  • 23 Forth
  • 24 Fortran
  • 25 FreeBASIC
  • 26 FutureBasic
  • 27 GlovePIE
  • 28 Go
  • 29 GW-BASIC
  • xxx Haskell
  • 31 Icon and Unicon
  • 32 Inform 7
  • 33 JavaScript
  • 34 Julia
  • 35 Kotlin
  • 36 Liberty Bones
  • 37 LiveCode
  • 38 Logo
  • 39 M2000 Interpreter
    • 39.1 Elementary Loop using Primal$
    • 39.2 Use a Office to return keypress and by reference return value
    • 39.3 Using Thread to read/write Keyboard buffer
    • 39.4 Using User Form (GUI)
  • 40 Mathematica/Wolfram Language
  • 41 Microsoft Small Basic
  • 42 MiniScript
  • 43 MUMPS
  • 44 NetRexx
  • 45 Nim
  • 46 NS-HUBASIC
  • 47 OCaml
  • 48 Oforth
  • 49 OpenEdge/Progress
  • 50 PARI/GP
  • 51 Pascal
  • 52 Perl
  • 53 Phix
  • 54 PicoLisp
  • 55 PL/I
  • 56 PowerShell
  • 57 PureBasic
  • 58 Python
  • 59 QB64
  • 60 QUACKASM
  • 61 Dissonance
  • 62 Raku
  • 63 REXX
    • 63.i version for all classic REXXes
    • 63.ii version 1 for PC/REXX and Personal REXX
    • 63.3 version 2 for PC/REXX and Personal REXX
  • 64 Band
  • 65 Ruby
  • 66 Run Basic
  • 67 Rust
  • 68 Scala
  • 69 Seed7
  • seventy Sidef
  • 71 Tcl
  • 72 TXR
  • 73 UNIX Shell
  • 74 VB-DOS
  • 75 Vedit macro language
  • 76 Wee Bones
  • 77 Wren
  • 78 XPL0
  • 79 Z80 Assembly

8080 Associates [edit]

This plan uses CP/One thousand to read the keyboard.

rawio:	equ	6	; Raw console input
puts: equ nine ; Cord output
bdos: equ v ; CP/M entry betoken
org 100h
jmp demo
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Routine: read 'Y' or 'Due north' from the keyboard.
;;; Output: carry flag clear if Y pressed, prepare if Northward pressed.
yesno: mvi c,rawio ; Read input from console
mvi e,-1
call bdos
ana a ; Read keys as long equally a cardinal is pressed
jnz yesno ; (await until keyboard is articulate)
yread: mvi c,rawio ; Then, await for a key to exist pressed
mvi e,-1
telephone call bdos
ana a
jz yread
ori 32 ; Fix bit 5 to make input letters lowercase
cpi 'y' ; If the key is Y,
rz ; and then return (carry is clear here)
cpi 'due north' ; If the key is N,
stc ; so set the carry flag and return
rz
jmp yread ; If it wasn't Y or N, go another fundamental
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Demo code: utilise the routine to read Y or N, and then print
;;; 'yes' or 'no'.
demo: call yesno ; Read Y or N
mvi c,puts
lxi d,yeah
jnc bdos ; If carry articulate, impress 'Yeah'
lxi d,no
jmp bdos ; Otherwise, print 'No'
yeah: db 'Yeah$'
no: db 'No$'

8086 Assembly [edit]

Assembled using UASM v2.49
          .model          small          
. stack 1024

  .data

  ;no data needed

  . code

first :
mov ax ,@code
mov ds , ax

  phone call PRIMM
BYTE "Leave program and return to MS-DOS? (Y/N)" , 0

  mov ax , 0C00h
int 21h ;flush keyboard buffer

 forever:
call waitKey
;returns ASCII code in AL

  and AL , 11011111b ;ignore case
cmp al , "Y"
jz ReturnToMSDOS

  cmp al , "Due north"
jz forever
;normally this would jump somewhere else but for simplicity it will wait
;for a yes response.
jnz forever

 ReturnToMSDOS:
mov ax , 0C00h
int 21h ;flush keyboard buffer

  mov ax , 4C00h
int 21h ;stop programme
;-------------------------------------------------------------------
; SUBROUTINES
;-------------------------------------------------------------------
waitKey:
mov ah , 01h
int 16h
jz waitKey
ret
;waits until a key is pressed.
;return:
; AL = ASCII CODE
; AH = SCAN CODE (???)

;-------------------------------------------------------------------
PrintString: ;Impress null-terminated strings
;input: string accost = ds:si

  lodsb ;Load a letter
cmp al , 0 ;Was that letter of the alphabet the terminator?
jz PrintString_Done ;Yeah? and so RET
call PrintChar ;Impress to screen
jmp PrintString ;Repeat
PrintString_Done:
ret
;-------------------------------------------------------------------
PrintChar:
push ax
mov ah , 0Eh
int 10h ;print AL to the screen.
pop ax
ret
;-------------------------------------------------------------------

 PrintSpace:
mov al , ' '
jmp PrintChar ;JMP avoids a tail call.
;ret ;"PrintChar"'s ret volition do this for united states of america.

;-------------------------------------------------------------------
NewLine:
push dx
button ax
mov ah , 02h
mov dl , 13 ;CR
int 21h
mov dl , 10 ;LF
int 21h
pop ax
pop dx
ret
;-------------------------------------------------------------------
PRIMM:
pop si
button ax
;go return address in si, this is the source first for
;the string that will be printed.
;String must be nada terminated.
phone call PrintString
pop ax
push button si
;PrintString adjusts the return address for us, information technology is at present
;merely later on the nada terminator. And then put it dorsum on the stack.
ret

;-------------------------------------------------------------------

   end commencement

8th [edit]


\ go a yep or no response from the keyboard
: aye-no
con:key $xx bor
dup 'y n:= if ;; then
dup 'north n:= if ;; then
drop yes-no ;
: no? 'n n:= if "No" else "Yeah" and so . ;

 "Yes or no? " con:print yes-no no?
cr bye

Action! [edit]

PROC Main()
Byte Central=764

  Printe("Press Y or Northward to continue")

  cardinal=255

  Practice
Until Central=43 or Key=35
Od

  Impress("You pressed ")
If Key=43 then Printe("Yes") Fi
If Key=35 then Printe("No ") Fi

 RETURN

Ada [edit]

          function          Yes_Or_No          (Prompt : String :=          "Your answer (Y/N): "          )          render          Boolean          is          
Answer : Grapheme;
brainstorm
Ada.Text_IO.Put (Prompt);
loop
Ada.Text_IO.Get_Immediate (Reply);
case Reply is
when 'Y'|'y' => render Truthful;
when 'Due north'|'n' => return False;
when others => null;
end example;
finish loop;
end Yes_Or_No;

AutoHotkey [edit]

          Loop          ,          {          
Input , Key, L1
if (Central = "n" || Primal = "y" )
break
}
MsgBox , % "The response was " "" Key "" "."
ExitApp

AWK [edit]


# syntax: GAWK -f KEYBOARD_INPUT_OBTAIN_A_Y_OR_N_RESPONSE.AWK
BEGIN {
printf ( "you entered %s\n",prompt_user( ) )
exit( 0 )
}
function prompt_user( rec) {
# AWK lacks the ability to get keyboard input without pressing the enter primal.
while ( i ) {
printf ( "enter Y or North " )
getline rec < "con"
gsub ( / /,"",rec) # optional
if (rec ~ /^ [nyNY]$/ ) {
interruption
}
}
render (rec)
}
enter Y or N y you entered y        

Axe [edit]

Since the TI-83/84 crave a modifier cardinal to access the letters, this example uses the 2nd key as Y and the Clear key every bit N.

While getKey(0)
Stop

 While i
If getKey(15)
Disp "N",i
Return
ElseIf getKey(54)
Disp "Y",i
Return
End
Finish

BASIC [edit]

Applesoft BASIC [edit]

10  LET C =  PEEK (49168): REM Articulate KEYBOARD
xx Impress "PRESS Y OR N TO Proceed"
30 Go K$
xl IF Thou$ < > "Y" AND K$ < > "N" And then xxx
50 PRINT "THE RESPONSE WAS ";K$

BASIC256 [edit]

          print          "Practise you want to continue y/n : ";
exercise
KBD$ = key
until KBD$ = "89" or KBD$ = "78"

impress chr (KBD$)

if KBD$ = "89" and then
print "OK, continuing"
else
print "OK, finishing"
finish if

QBasic [edit]

          PRINT          "Press Y or N to proceed."          
DO
KBD$ = ""
WHILE KBD$ = ""
KBD$ = UCASE$ ( INKEY$ )
WEND
IF KBD$ <> "Y" AND KBD$ <> "North" THEN BEEP
LOOP UNTIL KBD$ = "Y" OR KBD$ = "Due north"
PRINT "The response was "; KBD$

BBC Basic [edit]

          Echo UNTIL INKEY$(0) = ""
Print "Press Y or N to continue"
Echo
fundamental$ = GET$
UNTIL key$="Y" OR key$="N"
PRINT "The response was " fundamental$

Commodore BASIC [edit]

ten PRINT "PRESS Y OR Due north TO Keep:";
xx POKE 198, 0: REM Articulate KEY BUFFER
thirty GET Chiliad$
forty IF K$ <> "Y" AND K$ <> "N" THEN 30
50 Print K$

Note that 198 is the location of the keyboard buffer index on the VIC-20, C-64, and C-128. On the PET, the right location is 158, while on the Plus/four and C-16, it's 239.

The loop on lines xxx - 40 will bicycle as fast equally the interpreter can become, assigning 1000$ the empty cord until the user presses a fundamental. On versions of BASIC later than the two.0 on the VIC and 64 (e.g. three.5 on the C-sixteen and Plus/4, vii.0 on the C-128), GETKEY may be used in identify of GET. GETKEY will wait for the user to press a fundamental before standing, then the polling is washed in the BASIC interpreter'south automobile linguistic communication lawmaking, and the Bones loop simply cycles when the user presses a key other than Y or N.

GW-BASIC [edit]

          ten          CLS:          PRINT          "Press Y or North to continue."          
20 WHILE T$<> "y" AND T$<> "Y" AND T$<> "due north" AND T$<> "Northward"
30 T$= ""
40 WHILE T$= ""
50 T$ = INKEY$
lx WEND
70 IF T$<> "y" AND T$<> "Y" AND T$<> "due north" AND T$<> "Due north" THEN BEEP
80 WEND
90 PRINT "The response was "; T$

GW-BASIC variant [edit]

          10          DEF          FNUP$(C$)          =          CHR$(          ASC          (C$)          -          32          *          (          ASC          (C$)          >          96          )          *          (          ASC          (C$)          <          123          )          )          
twenty CLS: Impress "Press Y or North to continue."
thirty WHILE T$<> "Y" AND T$<> "N"
40 T$=FNUP$( INPUT$( ane ) )
fifty IF T$<> "Y" AND T$<> "N" And so BEEP
60 WEND
70 PRINT "The response was: "; T$

IS-BASIC [edit]

100 Get K$ ! Flush the keyboard buffer
110 Impress "Press Y or N to continue."
120 DO
130 LET Chiliad$=LCASE$(INKEY$)
140 LOOP UNTIL 1000$="y" OR K$="northward"
150 Impress "The response was ";Grand$

Locomotive Bones [edit]

          10          Articulate          INPUT          
twenty Impress "Press Y or N to continue"
30 a$=LOWER$( INKEY$)
40 IF a$="" THEN xxx
50 IF a$="y" So Print "Yep":Finish
60 IF a$="n" THEN Impress "No":END
70 PRINT "Try again"
fourscore GOTO xxx

Yabasic [edit]

clear screen

 impress "Do you want to go on y/n : ";

 repeat
KBD$ = lower$(inkey$)
until KBD$ = "y" or KBD$ = "n"

 print KBD$
if KBD$ = "y" and then
print "OK, continuing"
else
print "OK, finishing"
cease if

ZX Spectrum Basic [edit]

Note that this will as well work in GW-BASIC and most QBasic-compatible Basics if all instances of "Become TO" are changed to "GOTO".

          10          IF          INKEY$<>          ""          And then          GO          TO          10: REM flush the keyboard buffer
20 Print "Press Y or North to continue"
30 Allow m$ = INKEY$
forty IF k$ <> "y" AND k$ <> "Y" AND k$ <> "n" AND grand$ <> "N" So Become TO 30
50 Print "The response was "; g$

Batch File [edit]


@ echo off
choice
if errorlevel 2 echo You chose Northward
if errorlevel ane echo You chose Y
> nul pause

C [edit]

For POSIX compliant systems (in theory that includes WinNT family).


#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/time.h>

void set_mode( int want_key)
{
static struct termios old, new;
if ( !want_key) {
tcsetattr(STDIN_FILENO, TCSANOW, &old) ;
return ;
}

  tcgetattr(STDIN_FILENO, &old) ;
new = one-time;
new.c_lflag &= ~(ICANON) ;
tcsetattr(STDIN_FILENO, TCSANOW, &new) ;
}

int get_key( int no_timeout)
{
int c = 0 ;
struct timeval tv;
fd_set fs;
tv.tv_usec = telly.tv_sec = 0 ;

  FD_ZERO( &fs) ;
FD_SET(STDIN_FILENO, &fs) ;

  select(STDIN_FILENO + 1 , &fs, 0 , 0 , no_timeout ? 0 : &tv) ;
if (FD_ISSET(STDIN_FILENO, &fs) ) {
c = getchar ( ) ;
set_mode( 0 ) ;
}
return c;
}

int main( )
{
int c;
while ( i ) {
set_mode( i ) ;
while (get_key( 0 ) ) ; /* clear buffer */
printf ( "Prompt once more [Y/N]? " ) ;
fflush (stdout) ;

  c = get_key( 1 ) ;
if (c == 'Y' || c == 'y' ) {
printf ( "\n" ) ;
continue ;
}

  if (c == 'Due north' || c == 'due north' ) {
printf ( "\nDone\n" ) ;
break ;
}

  printf ( "\northwardYes or no?\n" ) ;
}

  return 0 ;
}

C# [edit]

using System;          

 namespace Y_or_N
{
class Program
{
static void Main( )
{
bool response = GetYorN( ) ;
}

  static bool GetYorN( )
{
ConsoleKey response; // Creates a variable to hold the user'southward response.

  do
{
while (Console.KeyAvailable ) // Flushes the input queue.
Console.ReadKey ( ) ;

  Console.Write ( "Y or North? " ) ; // Asks the user to answer with 'Y' or 'North'.
response = Panel.ReadKey ( ).Primal ; // Gets the user's response.
Console.WriteLine ( ) ; // Breaks the line.
} while (response != ConsoleKey.Y && response != ConsoleKey.N ) ; // If the user did not reply with a 'Y' or an 'N', repeat the loop.

  /*
* Return true if the user responded with 'Y', otherwise false.
*
* We know the response was either 'Y' or 'North', so we can assume
* the response is 'Northward' if information technology is non 'Y'.
*/

return response == ConsoleKey.Y ;
}
}
}

C++ [edit]

Windows specific

          #include <conio.h>          
#include <iostream>

using namespace std;

int main( )
{
char ch;
_cputs( "Yep or no?" ) ;
do
{
ch = _getch( ) ;
ch = toupper ( ch ) ;
} while (ch! = 'Y' &&ch! = 'Northward' ) ;

  if (ch== 'Due north' )
{
cout << "Yous said no" << endl;
}
else
{
cout << "You said yes" << endl;
}
return 0 ;
}

Clojure [edit]

Annotation: If you lot run it with Leiningen, use the special trampoline run to prevent bug:

$ lein trampoline run

( ns yprompt.cadre
(:import jline.Concluding)
(:gen-grade ) )

( defn yes? [k]
( if ( or ( = k 89 ) ( = thou 121 ) ) true faux) )

( defn prompt [ ]
(println "\northPrompt once again [Y/Northward]?" )
( allow [term (Last/getTerminal)
ykey (aye? ( .readCharacter term System/in) ) ]
( if-not ykey
( recur )
(println "Aye!" ) ) ) )

( defn -main [ & args]
(prompt) )

Common Lisp [edit]

LispWorks [edit]

Version 1:


( defun rosetta-y-or-n ( )
(clear-input *query-io*)
(y-or-northward-p) )

Version two:


( defun y-or-n ( )
(clear-input *standard-input*)
(loop every bit dum = (format t "Y or Due north for yep or no: " )
as c = (read-char)
as q = ( and ( not ( equal c #\n) ) ( not ( equal c #\y) ) )
when q do (format t "~%Need Y or N~%" )
unless q return ( if ( equal c #\y) 'aye 'no) ) )

Version 1 and 2 work as required in a LispWorks GUI interface, i.e. they return immediately when the y or n keys are pressed, without waiting for the Enter key.

ncurses [edit]

When called from a REPL in a Linux terminal, y-or-n-p is line buffered, which means any input has to be confirmed by an Enter central.

In club to have keys bachelor immediately to the program, line buffering has to be disabled in the tty commuter. This tin be done by utilizing the ncurses terminal library available on well-nigh GNU/Linux systems. To interface ncurses from Lisp, the croatoan library can be used:

Version three:


( defun y-or-no ( )
(with-screen (scr : input-buffering nothing : input-blocking t)
(articulate scr)
( princ "Practise you desire to go along? [Y/N]" scr)
(refresh scr)
(event-case (scr event)
( (#\Y #\y) (render-from event-case t) )
( (#\Due north #\northward) (return-from upshot-case nix ) ) ) ) )

D [edit]

          import          std.stdio          :          stdout,          write,          writefln;          

extern (C) nothrow {
void _STI_conio( ) ;
void _STD_conio( ) ;
int kbhit( ) ;
int getch( ) ;
}

void primary( ) {
_STI_conio( ) ;
write( "Enter Y or N: " ) ;
stdout.flush ( ) ;

  int c;
do {
while ( !kbhit( ) ) { }
c = getch( ) ;

  // Visual feedback for each keypress.
write( cast ( char )c) ;
stdout.flush ( ) ;
} while (c != 'Y' && c != 'y' && c != 'N' && c != 'n' ) ;

  writefln( "\nResponse: %c" , cast ( char )c) ;
_STD_conio( ) ;
}

Enter Y or N: abcN Response: N

Delphi [edit]

Thanks for JensBorrisholt [1].


program Obtain_a_Y_or_N_response;

{$APPTYPE CONSOLE}

uses
System. Panel ;

role GetKey(acepted: string ) : Char ;
var
key: Char ;
brainstorm
while True exercise
begin
if Console. KeyAvailable then
begin
fundamental : = UpCase (Console. ReadKey ( ) . KeyChar ) ;
if pos (key, acepted) > 0 then
leave (key) ;
terminate ;
end ;
Result : = #0 ; // Never Enter status
end ;

begin
Console. WriteLine ( 'Press Y or North' ) ;
case GetKey( 'YN' ) of
'Y' :
Console. WriteLine ( 'Y'all pressed Yes' ) ;
'Due north' :
Panel. WriteLine ( 'You pressed No' ) ;
else
Panel. WriteLine ( 'We have a mistake' ) ;
terminate ;
Readln;
stop .

Printing Y ou N You pressed Yes

EGL [edit]

Works with: EDT

Works with: RBD

handler YesOrNoHandler type RUIhandler{initialUI =[ui], onConstructionFunction = start}

  ui Div { };

  const KEY_N int = 78;
const KEY_Y int = 89;

  function beginning()
document.onKeyDown = d_onKeyDown;
terminate

  function d_onKeyDown(eastward Issue in)

  instance (due east.ch)
when (KEY_N)
ui.innerText = "N pressed.";
when (KEY_Y)
ui.innerText = "Y pressed.";
cease

  east.preventDefault();

  end

 finish

Elm [edit]

import Char
import Graphics.Element exposing (Element, empty, show)
import Keyboard

  view : Int -> Element
view keyCode =
let
char =
Char.fromCode keyCode

  showChar =
toString >> ((++) "The terminal (y/due north) key pressed was: ") >> testify
in
case char of
'due north' ->
showChar char

  'y' ->
showChar char

  _ ->
empty

  main : Signal Chemical element
main =
Signal.map view Keyboard.presses

ERRE [edit]


!$KEY
................
! flush the keyboard buffer
! --------------------------------
! you can employ POKE(198,0) in C-64
! ERRE version
! --------------------------------
Echo
GET(K$)
UNTIL K$=""

 PRINT("Press Y or Northward to continue")
REPEAT
Become(Thousand$)
UNTIL INSTR("YyNn",K$)<>0
!
! with C-64 you lot must write a line like
! UNTIL Thousand$="Y" OR One thousand$="Northward"
!

 Impress("The response was ";Thousand$)
.................

!$Fundamental is a directive pragma: using it GET become an equivalent to Qbasic INKEY$, otherwise it's equivalent to QBasic INPUT$(1). !$Fundamental is also used to mantain portability with the C-64 version of ERRE language.

Euphoria [edit]

          integer          key

puts ( ane , "Your answer? (Y/N)\n" )
while get_key ( )!=- 1 do
terminate while

while ane exercise
key = get_key ( )
if primal!=- 1 and (key = 'Y' or key = 'y' or central = 'Northward' or key = 'n' ) and then
go out
end if
end while

printf ( 1 , "Your response was %s\northward" ,key)

F# [edit]

          open          Organization

permit rec yorn ( ) =
let rec flush ( ) = if Console.KeyAvailable so ignore (Console.ReadKey ( ) ) ; flush ( )
flush ( )

  printf "\nY or N? "
match Console.ReadKey ( ).Cardinal with
| ConsoleKey.Y -> 'Y'
| ConsoleKey.N -> 'N'
| _ -> yorn( )

 printfn "\nYour choice: %c" (yorn( ) )

Forth [edit]

: flush ( -- )  \ discard pending input
brainstorm fundamental? while key drib repeat ;

 : y-or-northward ( c-addr u -- f )
flush begin
cr 2dup type key bl or \ note 1.
dup [char] y = swap [char] north = over or \ note 2.
if nip nip exit then
drop again ;

 \ Notation 1. KEY BL OR returns a lowercase alphabetic character in the case that an
\ upper-case letter letter was entered, an unchanged lowercase letter in the
\ case that a lowercase letter was entered, and garbage otherwise. BL
\ returns the ASCII code for a space, 32, which is incidentally the
\ "scrap of divergence" between ASCII uppercase and lowercase letters.

 \ Annotation 2. this line has the stack effect ( x -- f1 f2 ), where F1 is
\ truthful only if x='y', and F2 is truthful but if 10='y' OR if x='n'.

 \ I recollect these expressions aren't too clever, only they _are_ rather
\ optimized for the job at hand. This might exist more conventional:

 : y-or-n ( c-addr u -- f )
affluent begin
cr 2dup type fundamental case
[char] y of 2drop true leave endof
[char] Y of 2drop true go out endof
[char] n of 2drop false exit endof
[char] N of 2drop false exit endof
endcase again ;

Fortran [edit]

Standard Fortran has no special I/O statements that allow asynchronous actions (such as the KeyPressed and ReadKey functions of Turbo Pascal), so input is awaited in the usual style and a prompt should be supplied to indicate to the reader that a response is awaited, otherwise the user will face up a blank screen with nothing happening and will have to guess what might be expected. Further, in that location is no scheme for knowing if impending input has been waiting in an input buffer since before the need for a question arose, so it is non possible to flush such lines before requesting the special input. Impatience at the screenface can prompt typing ahead so that the next command will be immediately available just incorrectly predictable input will probable wreck the run, though for aye/no responses you may be rescued if such input does non conform to the required form: the bad input volition exist ignored and the question asked afresh. Thus, the details of the specification cannot exist met via standard Fortran, though a given system may have special subroutines equivalent to KeyPressed, etc. available.

However, asking questions tin oft be useful when messing about with tests, etc., so some routines for this can aid. These were devised afresh at the Culham Scientific discipline Centre, so there was some language generality:


Graphic symbol * 120 FUNCTION Reply(QUERY) !Obtain a text in reply.
Concocted past R.N.McLean (whom God preserve), December MM.
CHARACTER * ( * ) QUERY !The question.
CHARACTER * 120 TEXT !Alas, oh for proper strings.
INTEGER MSG,KEYS,LSTNB !Permit's hope everyone has the aforementioned type.
Common /IOUNITS/ MSG,KEYS!Orifices.
WRITE (MSG,one ) QUERY( one :LSTNB(QUERY) ),"?" !So, splurt.
1 FORMAT (2A,$) !A trailing text literal may not exist rolled.
READ (KEYS,i ) TEXT !Dare non use REPLY itself. Some implementations boggle.
Respond = TEXT !Then, shuffle.
RETURN !Take that.
END !Others translate the reply.

  Existent * eight FUNCTION REPLYN(QUERY) !Obtain a number in reply.
Concocted by R.Due north.McLean (whom God preserve), December MM.
Grapheme * ( * ) QUERY !The question.
REAL X !The answer, presumably not 42.
INTEGER MSG,KEYS,LSTNB !Let's promise everyone has the same type.
COMMON /IOUNITS/ MSG,KEYS!Orifices.
ane WRITE (MSG,2 ) QUERY( one :LSTNB(QUERY) ) !No trailing spaces.
ii FORMAT (A,$) !The $ patently suppresses the newline.
READ (KEYS,*,ERR = 3 ) Ten !Presume adequate testing for now.
REPLYN = X !The value!
RETURN !All washed.
3 WRITE (MSG,4 ) !Or perhaps not.
4 FORMAT ( 'Distasteful number. Try again...' ) !All sorts of ways.
Get TO ane !My patience is unconditional.
Finish !One way or another, a number will be secured.

  LOGICAL FUNCTION YEA(QUERY) !Obtain a Yep in reply?
Concocted by R.N.McLean (whom God preserve), Dec MM.
Graphic symbol * ( * ) QUERY !The question.
Grapheme * 120 WHAT,REPLY !Quite and then.
Grapheme * 1 C !Scratchpad.
INTEGER MSG,KEYS !Let'south hope anybody has the aforementioned blazon.
Mutual /IOUNITS/ MSG,KEYS!Orifices.
INTEGER L !A finger.
1 WHAT = REPLY(QUERY) !So, get an answer.
DO L = one,LEN (WHAT) !Sigh. Oh for Trim(string)
C = WHAT(L:L) !Sniff a CHARACTER.
IF (C .NE. ' ' ) Go TO 10 !A starter?
END Practice !No. Endeavor farther on.
WRITE (MSG,2 ) !Surely non.
2 FORMAT ( 'All blank?' ) !Poke.
3 WRITE (MSG,4 ) !Sigh.
iv FORMAT ( 'I dig it not. Try Yep/Si/Da/Oui/Ja, or No' )
GO TO ane !Go it correct, this fourth dimension?
x IF ( INDEX ( 'YySsDdOoJj',C) .GT. 0 ) THEN !Yes/Si/Da/Oui/Ja...
YEA = .TRUE. !A decision.
ELSE IF ( INDEX ( 'Nn',C) .GT. 0 ) THEN !No,No,Nyet,Non...
YEA = .Simulated. !Even if negative.
ELSE !Only if unrecognised,
Get TO 3 !Try again.
END IF !So much for choices.
RETURN !Laissez passer the discussion.
END !Enough of yes-beings.
LOGICAL FUNCTION NAY(QUERY) !Perhaps this reads better.
Concocted by R.N.McLean (whom God preserve), December MM.
CHARACTER * ( * ) QUERY !The question.
LOGICAL YEA !Let us hope and then.
NAY = .NOT.YEA (QUERY) !Straightforward.
Render !Laissez passer the inverted word.
Cease !So much for naysayers.

Usage might be something like IF (NAY("Keep the results")) CALL PURGE

FreeBASIC [edit]

          ' FB ane.05.0 Win64          

While InKey <> "" : Wend '' flush keyboard buffer
Print "Practise you desire to go along y/n : ";
Dim respond Every bit String

Practise
reply = LCase ( Inkey )
Loop Until respond = "y" OrElse respond = "due north"

Print answer '' echo response to panel
If answer = "y" So
Print "OK, continuing"
Else
Print "OK, finishing"
Stop If

Slumber

Sample input/output:

Do you desire to go along y/north : y OK, standing        

FutureBasic [edit]


local fn DoDialog
dim every bit long ev, id

 ev = dialog(0)
id = dialog(ev)

 select case( ev )
case _wndClose : cease
example _evKey
select id
// Trap upper and lower case Y and N
instance 78, 110 : cls : print "No "
case 89, 121 : cls : print "Aye"
finish select
terminate select
terminate fn

 on dialog fn DoDialog

 window one, @"Yes-No", (0,0)-(150,80), _docNoGrow
text _applFont, 14, _boldBit%

 RunApplicationEventLoop()

GlovePIE [edit]

if var.finish=0 then
var.cease=0
debug="Printing the Y fundamental or the N central to continue:"
endif
if pressed(Key.Y)and var.end=0 then
var.terminate=1
debug="You pressed the Y key."
endif
if pressed(Key.Due north)and var.end=0 then
var.finish=1
debug="You pressed the North cardinal."
endif

Go [edit]

          package          primary

import (
"log"

  gc "code.google.com/p/goncurses"
)

func main() {
southward, err := gc.Init()
if err != nil {
log.Fatal( "init:" , err)
}
defer gc.End()
var k gc.Key
for {
gc.FlushInput()
south.MovePrint( 20 , 0 , "Press y/n " )
s.Refresh()
switch k = s.GetChar(); k {
default :
continue
case 'y' , 'Y' , 'n' , 'N' :
}
suspension
}
s.Printf( "\nThanks for the %c!\n" , k)
due south. Refresh ()
due south. GetChar ()
}

                  package                  main
// siongui.github.io/2016/04/23/go-read-yep-no-from-panel
import (
"fmt"
"strings"
)

func ask() bool {
var s string
fmt.Printf( "(y/n): " )
fmt.Browse(&due south)
s = strings.TrimSpace(southward)
s = strings.ToLower(s)
if s == "y" || s == "yes" {
render true
}
render imitation
}

func principal() {
ans := ask()
if ans {
fmt.Println( "yes" )
} else {
fmt.Println( "no" )
}
}

GW-BASIC [edit]

          10          IF          INKEY$<>          ""          So          GOTO          ten: REM affluent the keyboard buffer
20 Impress "Press Y or Northward to go on"
30 Let k$ = INKEY$
40 IF k$ <> "y" AND 1000$ <> "Y" AND k$ <> "n" AND thou$ <> "N" THEN GOTO 30
50 Print "The response was "; chiliad$

Haskell [edit]

This may not be very idiomatic; it's pretty monad-oriented, and the use of exercise expressions makes the whole thing feel rather imperative.

          import          System.          IO          

 hFlushInput :: Handle -> IO ( )
hFlushInput hdl = do
r <- hReady hdl
if r then exercise
c <- hGetChar hdl
hFlushInput hdl
else
render ( )

 yorn :: IO Char
yorn = do
c <- getChar
if c == 'Y' || c == 'N' then return c
else if c == 'y' then return 'Y'
else if c == 'n' so return 'N'
else yorn

 main :: IO ( )
main = do
hSetBuffering stdout NoBuffering
putStr "Press Y or North to proceed: "

  hSetBuffering stdin NoBuffering
hSetEcho stdin False
hFlushInput stdin
answer <- yorn
putStrLn [answer]

Icon and Unicon [edit]

This solution works in both Icon and Unicon. It also accepts y or n.

          procedure          main(          )          
write ( "Response was " ,getResponse( "OK? (Y or North): " ) )
end

procedure getResponse(prompt)
while kbhit( ) practice getch ( ) # affluent input
writes (prompt)
repeat if map (answer := getch ( ) ) == ( "y" | "due north" ) then break
render answer
terminate

Inform 7 [edit]

Keyboard input goes through a virtual machine that'southward only required to provide blocking input operations, so flushing the buffer isn't possible.

Inform seven has a born function to ask the user for yes-or-no input, but it requires them to press enter after:

Qwantz is a room.

 When play begins:
say "A wizard has turned y'all into a whale. Is this awesome (Y/Due north)? ";
if the actor consents, say "Awesome!";
end the story.

To read a unmarried central without waiting for enter, we tin redefine the function past including a snippet of Inform half-dozen code:

To decide whether histrion consents: (- (YesOrNoKey()) -).

 Include (-
[ YesOrNoKey ch;
do { ch = VM_KeyChar(); } until (ch == 'y' or 'Y' or 'northward' or 'N');
return ch == 'y' or 'Y';
]; -).

JavaScript [edit]

Here's a synchronous ES6 implementation. The synchronous lawmaking must be executed in an async function definition. In this example, `wait_key` returns the key pressed and `washed` must exist chosen decouple the listening to stdin and terminate the process. The example pauses for a 2nd to show that the keys pressed before `wait_key` is called are non heard.

          const          readline          =          require(          'readline'          )          ;          
readline.emitKeypressEvents (procedure.stdin ) ;
procedure.stdin.setRawMode ( truthful ) ;

var wait_key = async function ( ) {
return await new Promise( function (resolve,reject) {
var key_listen = function (str,fundamental) {
procedure.stdin.removeListener ( 'keypress' , key_listen) ;
resolve(str) ;
}
procedure.stdin.on ( 'keypress' , key_listen) ;
} ) ;
}

var washed = function ( ) {
process.exit ( ) ;
}

var go = async function ( ) {
do {
console.log ( 'Printing any cardinal...' ) ;
var key = await wait_key( ) ;
console.log ( "Central pressed is" ,key) ;
await new Promise( function (resolve) { setTimeout(resolve, k ) ; } ) ;
} while(key != 'y' ) ;
washed( ) ;
}

 go( ) ;

Hither'southward how yous can asynchronously read a single grapheme in Node.js, using the keypress parcel. This does not seem to be possible to do synchronously in Node.js or at all in the SpiderMonkey shell.

          var          keypress          =          require(          'keypress'          )          ;          

 keypress(procedure.stdin ) ;

 procedure.stdin.on ( 'keypress' , function (ch, key) {
if (key && (key.name === 'y' || key.name === 'n' ) ) {
panel.log ( 'Reply:' + key.proper noun ) ;
}
} ) ;

 process.stdin.setRawMode ( true ) ;
process.stdin.resume ( ) ;

Using DOM events.

document.trunk.addEventListener          (          'keyup'          ,          function          (east)          {          
var primal = String.fromCharCode (e.keyCode ).toLowerCase ( ) ;
if (central === 'y' || cardinal === 'n' ) {
console.log ( 'response is: ' + primal) ;
}
} , simulated ) ;

Julia [edit]

Uses the Gtk library.

using Gtk.ShortNames

 function keypresswindow()

  # This code creates the Gtk widgets on the screen.
txt = "Blazon Y or Due north"
win = Window("Keypress Test", 250, 30) |> (Frame() |> ((vbox = Box(:v)) |> (lab = Label(txt))))

  # this is the keystroke processing lawmaking, a function and a callback for the function.
office keycall(w, effect)
ch = Char(event.keyval)
set_gtk_property!(lab,:label, ch in('north','Due north','y','Y') ? "You hit the $ch fundamental." : txt)
cease
Gtk.signal_connect(keycall, win, "fundamental-press-event")

  # this code sets upward a proper exit when the widow is closed.
c = Condition()
endit(westward) = notify(c)
Gtk.signal_connect(endit, win, :destroy)
Gtk.showall(win)
wait(c)
end

 keypresswindow()

Kotlin [edit]

          // version ane.0.6          

import java.awt.consequence.KeyAdapter
import java.awt.effect.KeyEvent
import javax.swing.JFrame
import javax.swing.SwingUtilities

class Test: JFrame( ) {
init {
while (Arrangement.`in`.available ( ) > 0 ) Organization.`in`.read ( )
println( "Practice you want to quit Y/Due north" )
addKeyListener( object : KeyAdapter( ) {
override fun keyPressed(e: KeyEvent) {
if (e.keyCode == KeyEvent.VK_Y ) {
println( "OK, quitting" )
quit( )
} else if (e.keyCode == KeyEvent.VK_N ) {
println( "Due north was pressed only the program is most to end anyway" )
quit( )
} else {
println( "Merely Y/North are adequate, please try again" )
}
}
} )
}

  private fun quit( ) {
isVisible = false
dispose( )
System.exit ( 0 )
}
}

 fun master(args: Array<String> ) {
SwingUtilities.invokeLater {
val f = Test( )
f.isFocusable = truthful
f.isVisible = true
}
}

Freedom Basic [edit]


nomainwin
open "Y/N" for graphics_nsb_nf as # 1
# 1 "trapclose Quit"
# 1 "down;setfocus;when characterInput KeyCheck"
# 1 "place 10 50;\Printing Y or N"
Inkey$ = ""
expect

sub KeyCheck hndle$,k$
one thousand$= upper$ (k$)
#hndle$ "cls;place ten 50"
select case g$
example "Y"
#hndle$ "\ Yes"
example "N"
#hndle$ "\No"
instance else
#hndle$ "\Incorrect input. Printing Y or N"
end select
end sub

sub Quit hndle$
close #hndle$
end
end sub

LiveCode [edit]

In the Card script, add a handler for the OpenCard result, putting empty into the text field.

In the text field, put the post-obit in its code

on KeyDown k
if toUpper(m) is among the items of "Y,N" then
answer "Thank you for your response"
else
respond "You need to enter Y or Due north"
stop if
put empty into me
end KeyDown

n.b. This sort of confirmation in GUI apps is usually presented as a dialog box with Aye/No buttons, which automatically handles keyboard input.

[edit]

to yorn
type [Press Y or North to proceed: ]
local "clear
make "clear readchars 0 ; clear input buffer
local "yorn
exercise.until [make "yorn readchar] [or equal? :yorn "Y equal? :yorn "N]
print :yorn
output :yorn
terminate

M2000 Interpreter [edit]

Unproblematic Loop using Key$ [edit]

If keyboard is Greek the we accept to change to English language. Other examples use Keyboard codes.


Module Simple {
\\ a small modification from BBC Bones entry
REPEAT {} UNTIL INKEY$ = ""
Print "Press Y or N to go along"
Echo {
thousand$ =Ucase$(Key$)
} UNTIL M$="Y" OR k$="Due north"
PRINT "The response was "; m$
}
Uncomplicated

Utilize a Function to render keypress and by reference return value [edit]


Module Checkit {
Function GetYN$ (&Ret) {
const Y=0x59
const N=0x4E
Ret=False
Do {
if keypress(Y) then Ret=True : exit
if keypress(Northward) then get out
driblet$=inkey$
} Always
K$=primal$
do {} until filter$(Inkey$,k$)=""
=Ucase$(K$)
}
keyboard "abcde" ' feed keyboard (inkey$ get these characters)
Y=0
Print "Your answer (Y/N):"; GetYN$(&Y)
Print Y
}
Checkit

Using Thread to read/write Keyboard buffer [edit]

We use a thread, using afterwards, for 1 run, after 10ms, when Input look for keypress. Then when telephone call to GetYN module exit has Y or N with Enter to keyboard. Now Input finish.

Threads runs in same namespace as the module they created. So module name and Y variable are visible.Module GetYN tin't read parent module variables, except M which declared equally GLOBAL. Afterwards 500ms N is returned.

Using Profiler and Impress Timecount we get the real duration (using high resolution timer), of response.


Module CheckisToo {
Module GetYN (&Ret) {
const Y=0x59
const Northward=0x4E
Ret=False
Do {
If Yard>50 then Keyboard "N" : exit
if keypress(Y) then Ret=True : get out
if keypress(N) then exit
drop$=inkey$
\\ ensure thread MM run using wait
wait 1
} Always
Keyboard Ucase$(Key$)+Chr$(13)
}
keyboard "abcde"
Y=0
Global Chiliad=0
Thread {
G++
} as MM interval 10
While Inkey$<>"" {}
Afterward 10 {
Module GetYN &Y
}
Profiler
Input "Your answer (Y/North):", A$
Print timecount
Impress Y, M
Threads Erase
}
CheckisToo

Using User Form (GUI) [edit]


Module UseUIForm {
Const Y=0x59, Due north=0x4E, Center=2
Ret=False
Declare Form1 form
Layer Form1 {
Window 22, 8000, 4000;
Cls #333333,0
Cursor 0, Height/2
Study Center, "Press (Y/N)"
}
Function form1.Keydown {
Read New &central, &shiftKey
IF central=Y and so ret=True : Method Form1, "CloseNow"
If fundamental=N Then Method Form1, "CloseNow"
}
Method Form1, "Prove", 1 ' modal show
Impress Ret
Declare Form1 Null
}
UseUIForm

Mathematica/Wolfram Language [edit]

CreateDialog[TextCell["Yes or no?[Y/N]"],
NotebookEventActions -> {
"KeyDown" :> Switch[[email protected]["EventKey"],
"Y", Print["Yous said yes"]; DialogReturn[],
"Due north", Print["You said no"]; DialogReturn[]
]}];

Microsoft Small Bones [edit]

Submitted by: AykayayCiti (Earl L. Montgomery) on Mar xix, 2018. In one case you hit a primal a separate dialog box volition announced. Place them side by side to see the results.

          'From:
'Andy Oneill, 2-6-2015, "Small Basic: Primal Input,
'" TechNet, https://social.technet.microsoft.com/wiki/contents/articles/29850.small-bones-primal-input.aspx, accessed iii-19-2018

GraphicsWindow.DrawText(10, 10, "Hit whatsoever key to dump.")
GraphicsWindow.KeyDown = OnKeyDown
Sub OnKeyDown
TextWindow.WriteLine(GraphicsWindow.LastKey)
EndSub

MiniScript [edit]

Access to hardware similar the keyboard is very dependent on the host app, just here'due south a version that works with MiniMicro, a standardized MiniScript virtual machine.

// affluent the keyboard
while key.bachelor
key.become
finish while

 // and now prompt and expect for Y or N
print "Press Y or Northward:"
k = ""
while chiliad != "Y" and k != "North"
1000 = key.go.upper
terminate while
print "Y'all pressed: " + 1000

MUMPS [edit]

Version from terminal shown below.

for  read !,"Enter Y or N to continue: ",input  quit:input?1(1"Y",ane"y",one"N",1"n")
Enter Y or N to continue: J          

Enter Y or North to continue: Yeah Enter Y or N to continue: no Enter Y or N to proceed: Due north

SAMPLES>

NetRexx [edit]

          /* NetRexx */          

 options replace format comments java crossref savelog symbols binary

Say 'Delight enter Y or N'
parse ask c
Select
when c='Y' Then Say 'YES'
when c='N' Then Say 'NO'
otherwise Say 'Undecided'
Terminate

Nim [edit]

Using "gintro" bindings to Gtk3.

import strformat
import gintro/[glib, gobject, gtk, gio]
import gintro/gdk except Window

 #---------------------------------------------------------------------------------------------------

 proc onKeyPress(window: ApplicationWindow; event: Consequence; label: Label): bool =
var keyval: int
if non consequence.getKeyval(keyval): return false
if keyval in [ord('n'), ord('y')]:
label.setText(&"Y'all pressed fundamental '{chr(keyval)}'")
effect = true

 #---------------------------------------------------------------------------------------------------

 proc actuate(app: Awarding) =
## Activate the application.

  allow window = app.newApplicationWindow()
window.setTitle("Y/North response")

  let hbox = newBox(Orientation.horizontal, 0)
window.add(hbox)
let vbox = newBox(Orientation.vertical, ten)
hbox.packStart(vbox, true, true, twenty)

  allow label1 = newLabel(" Press 'y' or 'north' primal ")
vbox.packStart(label1, true, true, 5)

  let label2 = newLabel()
vbox.packStart(label2, truthful, true, 5)

  discard window.connect("key-printing-upshot", onKeyPress, label2)

  window.showAll()

 #———————————————————————————————————————————————————————————————————————————————————————————————————

 let app = newApplication(Awarding, "Rosetta.YNResponse")
discard app.connect("activate", activate)
discard app.run()

NS-HUBASIC [edit]

10 PRINT "Printing Y OR Northward TO CONTINUE."
20 IF INKEY$<>"Y" AND INKEY$<>"N" And so GOTO 20
thirty PRINT "THE RESPONSE WAS ";INKEY$;"."

OCaml [edit]

Unix module, exposing POSIX interfaces like termios, is usually bundled with any standard OCaml distribution. Utilizing termios is the solution many other linguistic communication examples here went with.

OCaml needs to link to the arranged unix archives correctly in order to compile / run lawmaking that uses definitions inside the module. To do this with the plain OCaml toolchain, recall to add the library archive to the commandline similar so:

ocaml unix.cma <yourfile.ml> interpreted
ocamlc -o <progname> unix.cma <yourfile.ml> bytecode executable
ocamlopt -o <progname> unix.cmxa <yourfile.ml> native executable

Here nosotros ascertain some helper functions that nosotros'll use:

          allow          attrs          =          Unix          .          (tcgetattr          stdin          )          
permit buf = Bytes.create 1

permit prompt switch =
Unix . (tcsetattr stdin TCSAFLUSH)
@@ if switch then { attrs with c_icanon = imitation } else attrs

let getchar ( ) =
let len = Unix . (read stdin ) buf 0 ane in
if len = 0 then enhance End_of_file else Bytes.get buf 0

Now the main program:

          permit          rec          loop          (          )          =          
print_string "Prompt? [Y/North]: " ; flush stdout ;
loop
@@ print_endline
@@ lucifer getchar ( ) with
| 'due north' | 'N' -> raise Exit
| 'y' | 'Y' -> ": Ok."
| _ -> ": Invalid."

let _ = try loop @@ prompt true with Exit | End_of_file -> prompt faux

Oforth [edit]

import: panel

 : YorN
| c |
System.Console flush
doWhile: [
System.Panel receiveChar toUpper ->c
c 'Y' <> c 'Northward' <> and
]
c ;

OpenEdge/Progress [edit]

          DEF          VAR          lanswer          As          LOGICAL          INITIAL          ?.          

DO WHILE lanswer = ?:
READKEY .
IF CHR ( LASTKEY ) = "n" OR CHR ( LASTKEY ) = "y" THEN
lanswer = CHR ( LASTKEY ) = "y" .
Terminate .

MESSAGE lanswer VIEW-AS Alert-BOX .

PARI/GP [edit]

GP's input is non able to read an unbuffered single graphic symbol, so one must use PARI where the solution is identical to that of C.

Pascal [edit]

          Plan          ObtainYN;          

uses
crt;

var
key: char ;

begin
write ( 'Your respond? (Y/N): ' ) ;
repeat
key : = readkey;
until (fundamental in [ 'Y' , 'y' , 'N' , 'n' ] ) ;
writeln ;
writeln ( 'Your answer was: ' , key) ;
terminate .

Output:

% ./ObtainYN Your answer? (Y/North):  Your respond was: y        

Perl [edit]

          use          Term::          ReadKey          ;          

 ReadMode 4 ; # alter to raw input mode

my $central = '' ;

while ( $key !~ /(Y|N)/i ) {
1 while defined ReadKey - ane ; # discard whatsoever previous input
print "Type Y/N: " ;
$fundamental = ReadKey 0 ; # read a single graphic symbol
print "$key\due north" ;
}

 ReadMode 0 ; # reset the terminal to normal mode

print "\due northYou typed: $primal\northward" ;

Phix [edit]

For 1970s-mode graphic symbol console (/beginner) applications:

          integer          key          while          get_key          ()!=-          1          do          finish          while          -- flush          puts          (          one          ,          "Your respond? (Y/N)"          )          while          1          practise          cardinal          =          upper          (          get_key          ())          if          discover          (          key          ,          "YN"          )          then          exit          end          if          end          while          printf          (          1          ,          "\nYour response was %s\n"          ,          key          )        

For GUI (graphical user interface) applications, use something more like this:

          function          key_cb          (          Ihandle          /*ih*/          ,          cantlet          c          )          if          lower          (          c          )=          'y'          then          y_keyed          ()          stop          if          if          lower          (          c          )=          'n'          then          n_keyed          ()          end          if          return          IUP_CONTINUE          terminate          role          IupSetCallback          (          dlg          ,          "K_ANY"          ,          Icallback          (          "key_cb"          ))        

See Keyboard_macros#Phix or Conway's_Game_of_Life#Phix for a more complete example

PicoLisp [edit]

(de yesno ()
(loop
(NIL (uppc (key)))
(T (= "Y" @) T)
(T (= "Due north" @)) ) )

PL/I [edit]

          yn:          Proc          Options          (          chief          )          :          
Dcl sysin stream input ;
Dcl sysprint stream output ;
Dcl c Char ( 1 ) ;
Put Skip Listing ( 'Delight enter Y or N' ) ;
Get Edit (c) (a( 1 ) ) ;
Select (c) ;
When ( 'Y' , 'y' , 'J' , 'j' )
Put Skip List ( 'YES' ) ;
When ( 'North' , 'n' )
Put Skip List ( 'NO' ) ;
Otherwise
Put Skip List ( 'Undecided?' ) ;
Cease ;
Finish ;

PowerShell [edit]

This is for console use just. The ISE is geared for a different type of input.


do
{
$keyPress = [Arrangement.Console]::ReadKey( )
}
until ( $keyPress.Primal -eq "Y" -or $keyPress.Key -eq "Due north" )

$keyPress | Format-Tabular array -AutoSize

If the user pressed the "Y" cardinal...

KeyChar Key Modifiers ------- --- ---------       y   Y         0        

If the user pressed the "N" key...

KeyChar Key Modifiers ------- --- ---------       n   Northward         0        

PureBasic [edit]

Inkey() returns the character string of the key which is being pressed at the time.

          PrintN          (          "Press Y or N to continue"          )          

Repeat
; Become the fundamental being pressed, or a empty string.
Cardinal$= UCase ( Inkey ( ) )
;
; To Reduce the problems with an active loop
; a Filibuster(one) will release the CPU for the rest
; of this quanta if no key where pressed.
Delay ( 1 )
Until Primal$= "Y" Or Primal$= "North"
PrintN ( "The response was " +Key$)

Python [edit]

          #!/usr/bin/env python          

try:
from msvcrt import getch
except ImportError:
def getch( ):
import sys , tty , termios
fd = sys.stdin.fileno ( )
old_settings = termios.tcgetattr (fd)
endeavour:
tty.setraw ( sys.stdin.fileno ( ) )
ch = sys.stdin.read ( i )
finally:
termios.tcsetattr (fd, termios.TCSADRAIN , old_settings)
return ch

print "Press Y or Due north to go along"
while True:
char = getch( )
if char.lower ( ) in ( "y" , "north" ):
print char
break


          #!/usr/bin/env python          
# -*- coding: utf-eight -*-
from curses import wrapper
#
#
def main(stdscr):
# const
#y = ord("y")
#n = ord("n")
while True:
# keyboard input interceptor|listener
#window.nodelay(yep)
# - If yep is 1, getch() will exist non-blocking.
# return char code
#kb_Inpt = stdscr.getch()
# return string
kb_Inpt = stdscr.getkey ( )
#if kb_Inpt == (y or n):
if kb_Inpt.lower ( ) == ( 'y' or 'north' ):
break
return None
#
return None
#
#*** unit test ***#
if __name__ == "__main__":
#
wrapper(main)

QB64 [edit]

CBTJD: 2020/03/fifteen

          WHILE          INKEY$          <>          "":          WEND          '                                  Flushes keyboard buffer.          
PRINT "Do y'all want to keep? (Y/Northward)"
DO
k$ = UCASE$ ( INKEY$ ) ' Forces key response to upper example.
LOOP UNTIL yard$ = "Y" OR k$ = "N"
PRINT "You pressed " + CHR$ ( 34 ) + k$ + CHR$ ( 34 ) + "." ' CHR$(34) prints quotation marks.

QUACKASM [edit]

Note: The following is not a total program (it is only a subroutine, using standard calling conventions), nor does it flush the keyboard buffer (in that location is no standard way to do this in QUACKVM; it may be possible using extensions, merely none are currently defined).


; Stores result in cell 2; 1 if yes, 0 if no.
:YORN
PRINT YORNMSG
:YORN1
INPUT >2
AND *2,$5F,'Y >2 /YORN2
AND *2,,'Northward \YORN1
:YORN2
PRINTC *2
PRINTC 13
AND *ii,1 >two
Render
:YORNMSG " (Y/Due north)? \

Racket [edit]


#lang racket

 ;; GUI version
(crave racket/gui)
(message-box "Yes/No example" "Yes or no?" #f '(yes-no))

 ;; Text version, via stty
(define stty
(let ([exe (find-executable-path "stty")])
(λ args (void (apply organisation* exe args)))))
(define tty-settings (cord-trim (with-output-to-string (λ() (stty "-chiliad")))))
(printf "Yep or no? ") (affluent-output)
(stty "-icanon" "-echo" "min" "i")
(let loop () (when (char-ready?) (loop)))
(let loop ()
(define ch (read-char))
(instance (char-downcase ch)
[(#\y #\Y #\n #\Northward) (displayln ch) (if (memq ch '(#\y #\Y)) 'aye 'no)]
[else (loop)]))
(stty tty-settings)

Raku [edit]

(formerly Perl vi)

          my          $TTY          =          open up(          "/dev/tty"          )          ;          

sub prompt-char( $prompt ) {
ENTER shell "stty raw -echo min 1 fourth dimension one" ;
LEAVE beat out "stty sane" ;

  print $prompt ;
$TTY . read ( 1 ) . decode ( 'latin1' ) ;
}

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

REXX [edit]

version for all archetype REXXes [edit]

This version works with all archetype REXXes.

REXX (in full general) requires the user to press the ENTER key after inbound text.
This is because the original (IBM) REXX was designed and written for a arrangement when all I/O to a user'south concluding screen was
in block mode and required the user to printing 1 of the following before any information was sent to the computer:

  • the ENTER cardinal
  • a PF (programme function fundamental)
  • a PA (program assist central)
  • the ATTN (attention) key
  • perhaps some other special key(south)


Annotation that the above keys may have unlike names on terminals that emulate an IBM 3270 type terminal (block mode terminals).
Some older Classic REXX interpreters accept a keyboard read subroutine (BIF) and then that the plan can read keyboard keys as
they are pressed   (see the other versions below).

          /*REXX plan tests for a    Y  or  Due north    cardinal when entered from keyboard after a prompt.*/          

  practice queued ( ); pull; end /*affluent the stack if annihilation is queued*/

 prompt = 'Please enter Y or N for verification:' /*this is the PROMPT message.*/

  practise until pos (ans,'NY' ) \==0 & length (ans)==1 /*keep looking for a Y or Northward answer.*/
say; say prompt /*brandish bare line; brandish prompt. */
pull ans /*get the reply(s) and uppercase it.*/
ans=space (ans, 0 ) /*elide all blanks. */
end /*until*/
/*stick a fork in it, we're all done. */

version one for PC/REXX and Personal REXX [edit]

This version of a REXX program works with PC/REXX and Personal REXX.

          /*REXX programme tests for a    Y  or  N    key when entered from keyboard afterward a prompt.*/          
prompt = 'Delight enter Y or N for verification:' /*this is the PROMPT message.*/

  practise until pos (ans, 'NYny' ) \== 0 /*keep prompting until answer= Y North y due north */
say; say prompt /*brandish blank line; display prompt. */
ans=inKey( 'wait' ) /*become the reply(southward) from the terminal. */
end /*until*/
/*stick a fork in it, nosotros're all done. */

version ii for PC/REXX and Personal REXX [edit]

This version is the aforementioned equally above, simply has a more idiomatic technique for testing the response.

          /*REXX programme tests for a    Y  or  Northward    cardinal when entered from keyboard later a prompt.*/          
prompt = 'Delight enter Y or N for verification:' /*this is the PROMPT bulletin.*/

  practice until pos (ans, 'NY' ) \==0 /*keep prompting 'til user answers Y│N */
say; say prompt /*display blank line; display prompt. */
ans=inKey( 'wait' ); upper ans /*get the answer(s); and capital it.*/
cease /*until*/
/*stick a fork in information technology, we're all washed. */

Ring [edit]


while truthful
give c
if c = "Y" see "Yous said yeah!" + nl
but c = "N" see "You said no!" + nl
else see "Try again!" + nl ok
end

Ruby [edit]


def yesno
brainstorm
system ( "stty raw -echo" )
str = STDIN.getc
ensure
organization ( "stty -raw repeat" )
finish
if str == "Y"
return true
elsif str == "Due north"
render fake
else
raise "Invalid grapheme."
end
end

Ruby provides the io/console module since version 2.0:


require 'io/panel'

def yesno
example $stdin.getch
when "Y" and so true
when "Northward" and then false
else raise "Invalid character."
end
end

Run Basic [edit]

[loop] cls                ' Clear screen
html "Click Y or N" ' no other options
button #y, "Y", [Y] ' they either click [Y]
button #n, "N", [N] ' or they click [N]
html "<br>";msg$ ' impress message showing what they entered
wait
[Y] msg$ = "You entered [Y]es": goto [loop]
[N] msg$ = "Yous entered [N]o" : goto [loop]

Rust [edit]

//cargo-deps: ncurses

 extern crate ncurses;
use ncurses::*;

 fn main() {
initscr();
loop {
printw("Yes or no? ");
refresh();

  lucifer getch() as u8 as char {
'Y'|'y' => {printw("You said yes!");},
'Due north'|'due north' => {printw("You said no!");},
_ => {printw("Try once again!\n"); proceed;},
}
break
}
refresh();
endwin();
}

Scala [edit]

          println(          if          (scala.io.StdIn.readBoolean          )          "Yes typed."          else          "Something else."          )        


import coffee.io.InputStreamReader
val in = new InputStreamReader(System.in )
if (Seq( 121, 89, 110, 78 ).contains (in.read ( ) ) ) {println( "Yes|No" ) } else {println( "other" ) }


import scala.io.{Source, BufferedSource}
val kbd_In: BufferedSource = Source.stdin
//kbd_In.next()
//res?: Char = 'y' non :String = "y"
if (Seq( 'y', 'Y', 'n', 'Y' ).contains (kbd_In.next ( ) ) ) {println( "Typed y|Y|north|Northward" ) } else {println( "other fundamental" ) }

Seed7 [edit]

$ include "seed7_05.s7i";
include "keybd.s7i";

 const func boolean: yesOrNo (in cord: prompt) is func
result
var boolean: yes is Fake;
local
var char: answer is ' ';
begin
while keypressed(KEYBOARD) do
ignore(getc(KEYBOARD));
end while;
write(prompt);
repeat
respond := lower(getc(KEYBOARD));
until answer in {'y', 'n'};
yep := respond = 'y';
end func;

 const proc: main is func
begin
writeln(yesOrNo("Press Y or North to continue "));
end func;

Sidef [edit]

Translation of: Perl

func prompt_yn          {          
static rk = frequire( 'Term::ReadKey' );
rk.ReadMode ( four ); # change to raw input manner

  var key = '';
while (cardinal !~ / [yn] /i) {
while (rk.ReadKey ( - ane ) != nil ) { }; # discard any previous input
print "Type Y/N: ";
say (key = rk.ReadKey ( 0 ) ); # read a unmarried character
}

  rk.ReadMode ( 0 ); # reset the terminal to normal mode
return key.uc;
}

 var key = prompt_yn( );
say "You lot typed: #{key}";

Type Y/N: a Blazon Y/Northward: b Type Y/North: c Type Y/N: y You typed: Y        

Tcl [edit]

Using the console (expects U*Xish stty)

          proc          yesno          {          {message          "Printing Y or Due north to continue"          }          }          {          
fconfigure stdin -blocking 0
exec stty raw
read stdin ; # flush
puts -nonewline "${bulletin}: "
flush stdout
while { ! [ eof stdin] } {
set c [ cord tolower [ read stdin 1 ] ]
if { $c eq "y" || $c eq "north" } break
}
puts [ string toupper $c ]
exec stty -raw
fconfigure stdin -blocking i
return [ expr { $c eq "y" } ]
}

set yn [yesno "Do you lot similar programming (Y/Northward)" ]

Without a console (answer in the global variable yn; this should work in any GUI for which in that location is a TCL):


proc yesno {bulletin} {
toplevel .msg
pack [label .msg.l -text "$bulletin\northward (blazon Y/Due north)?" ]
set ::yn ""
bind .msg <Key-y> { set ::yn "Y" }
demark .msg <Key-n> { set ::yn "N" }
vwait ::yn
destroy .msg
}

 yesno "Do you like programming?"

TXR [edit]

This works not only on Unix-like platforms, only likewise on Microsoft Windows, because TXR is ported to Windows using a modified version of Cygwin.

(with-resource ((tio-orig (tcgetattr) (tcsetattr tio-orig)))
(let ((tio (copy tio-orig)))
tio.(become-raw)
(tcsetattr tio tcsaflush) ;; third arg optional, defaults to tcsadrain
(whilet ((k (get-char))
((not (member k '(#\y #\north #\Y #\Northward))))))))

The become-raw method on the termios construction only manipulates the construction contents; tcsetattr pushes information technology down to the TTY driver.

go-raw is defined in the TXR standard library similar this:

(defmeth termios get-raw (tio)
tio.(articulate-iflags ignbrk brkint parmrk istrip inlcr igncr icrnl ixon)
tio.(articulate-oflags opost)
tio.(articulate-cflags csize parenb)
tio.(articulate-lflags echo echonl icanon isig)
(if (boundp 'iexten)
tio.(clear-lflags iexten))
tio.(set-cflags cs8)
(fix tio.[cc vmin] i)
(prepare tio.[cc vtime] 0))

UNIX Trounce [edit]

getkey(          )          {          
local stty="$(stty -k)"
trap "stty $stty; trap SIGINT; return 128" SIGINT
stty cbreak -echo
local key
while true; do
key=$( dd count=1 two >/dev/null) || render $?
if [ -z "$1" ] || [ [ "$key" == [ $1 ] ] ]; then
break
fi
washed
stty $stty
repeat "$fundamental"
return 0
}

 yorn( ) {
echo -due north "${ane:-Press Y or N to continue: }" >& 2
local yorn="$(getkey YyNn)" || render $?
example "$yorn" in
[Yy] ) echo >& 2 Y; return 0 ;;
[Nn] ) echo >& 2 Northward; return 1 ;;
esac
}

Cleaner version using bash built-ins

#!/bin/bash

 yorn() {
echo -n "${1:-Press Y or N to continue: }"

  shopt -s nocasematch

  until [[ "$ans" == [yn] ]]
exercise
read -s -n1 ans
washed

  echo "$ans"

  shopt -u nocasematch
}

 yorn

VB-DOS [edit]

          OPTION          EXPLICIT          
DIM T AS INTEGER
T = MSGBOX("Click on yes or no", 4, "Option")
Print "The response is ";
IF T = half-dozen THEN PRINT "yes"; ELSE Print "no";
Print "."
END

Vedit macro linguistic communication [edit]

Key_Purge(          )          // flush keyboard buffer          
practise {
#one = Get_Key( "Are yous sure? (Y/North): " ) // prompt for a key
#1 &= 0xdf // to upper case
} while (#1 != 'Y' && #1 != 'N' )

Wee Bones [edit]

print i "Enter Y for yeah, or N for no. (not case sensitive)"
let loop=0
let keycode=0
while loop=0
allow keycode=primal()
if keycode=121
let response$="y"
let loop=1
elseif keycode=89
let response$="Y"
let loop=ane
elseif keycode=110
let response$="north"
let loop=1
elseif keycode=78
let response$="N"
let loop=1
endif
wend
print 1 "You lot entered"+response$
end

Wren [edit]

          import          "io"          for          Stdin,          Stdout

 Stdin. isRaw = true // input is neither echoed nor buffered in this mode

 Arrangement. print ( "Press Y or N" )
Stdout. flush ( )

var byte
while ( ( byte = Stdin. readByte ( ) ) && ! "YNyn" . bytes . contains ( byte ) ) { }
var yn = String . fromByte ( byte )
System. print (yn)

 Stdin. isRaw = simulated

Sample run:

Press Y or N y        

XPL0 [edit]

include c:\cxpl\codes;          \intrinsic 'code' declarations
loop [OpenI(one); \flush any awaiting keystroke
case ChIn(1) of \get keystroke
^Y,^y: Text(0, "yeah");
^Due north,^north: Text(0, "no");
$1B: quit \Esc central terminates program
other ChOut(0, vii\bel\);
CrLf(0);
]

Z80 Assembly [edit]

This simple template can be CALLed to wait for a Y/N response and act based on that. This particular template is express in that the lawmaking that gets executed based on the response can't exist inverse at runtime (at to the lowest degree not without cocky-modifying code.)

wait_for_key_input:
call &BB0 6 ;bios call, waits until key is pressed, returns cardinal'due south ASCII code into A
and %11011111 ;converts to upper case
cp 'Y'
jp z,User_Chose_Yes
cp 'N'
jp z,User_Chose_No
jp wait_for_key_input

 User_Chose_Yes:
;your code for what happens when the user types "Y" goes here
ret

 User_Chose_No:
;your code for what happens when the user types "Due north" goes here
ret

spectorcolon2001.blogspot.com

Source: https://rosettacode.org/wiki/Keyboard_input/Obtain_a_Y_or_N_response

0 Response to "N N N N Nothing There It Is Again"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel