Jump to content

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

more documentation plus some code prettifying
(more documentation plus some code prettifying)
Line 1,332:
 
=={{header|OCaml}}==
<code>Unix</code> librarymodule, exposing POSIX interfaces like [https://en.wikipedia.org/wiki/POSIX_terminal_interface termios], is normally bundled with any standard OCaml distribution. forUtilizing POSIXtermios interfacesis the solution many other language examples here went with.
Interfacing with [https://en.wikipedia.org/wiki/POSIX_terminal_interface termios] is specific to UNIX-likes.
 
OCaml needs to link to the bundled unix archives correctly in order to compile / run code that uses definitions within the module. To do this with the plain OCaml toolchain, remember to add the library archive to the commandline like so:
<lang OCaml>open Unix
type mode = Prompt | Input
let original_attrs = tcgetattr stdin
let set = function
| Prompt -> tcsetattr stdin TCSAFLUSH {original_attrs with c_icanon = false}
| Input -> tcsetattr stdin TCSAFLUSH original_attrs
let getchar buf =
if read stdin buf 0 1 = 0 then raise End_of_file
else Bytes.get buf 0</lang>
 
<code>ocaml unix.cma <yourfile.ml></code> interpreted<br/>
Main:
<code>ocamlc -o <progname> unix.cma <yourfile.ml></code> bytecode executable<br/>
<lang OCaml>let _main =
<code>ocamlopt -o <progname> unix.cmxa <yourfile.ml></code> native executable
let buf = Bytes.create 1 in
 
let rec prompt () =
Here we define some helper functions that we'll use:
print_string "Prompt? [Y/N]: ";
 
flush_all();
<lang OCaml>let attrs = Unix.(tcgetattr stdin)
set Prompt;
let buf = Bytes.create 1 in
match getchar buf with
 
| 'n'|'N' -> ();
let rec prompt ()switch =
| 'y'|'Y' -> print_endline ": Ok."; prompt ();
| Input -> Unix.(tcsetattr stdin TCSAFLUSH original_attrs)
| _ -> print_endline ": Invalid."; prompt ();
@@ if switch then { attrs with c_icanon = false } else attrs
set Input;
 
in
let getchar buf() =
prompt ()</lang>
let len = Unix.(read stdin) buf 0 1 in
if read stdinif buf 0 1len = 0 then raise End_of_file else Bytes.get buf 0</lang>
 
Now the main program:
<lang OCaml>openlet Unixrec loop () =
print_string "Prompt? [Y/N]: "; flush stdout;
loop
@@ print_endline
@@ match getchar buf() with
| 'n' | 'N' -> ();raise Exit
| 'y' | 'Y' -> print_endline ": Ok."; prompt ();
| _ -> print_endline ": Invalid."; prompt ();
 
let _ = try loop @@ prompt true with Exit | End_of_file -> prompt false</lang>
 
=={{header|Oforth}}==
13

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.