Keyboard input/Obtain a Y or N response: Difference between revisions
Content deleted Content added
Category:Keyboard Input -> Category:Keyboard input lowercase "input" |
more documentation plus some code prettifying |
||
Line 1,332:
=={{header|OCaml}}==
<code>Unix</code>
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▼
| Input -> tcsetattr stdin TCSAFLUSH original_attrs▼
let getchar buf = ▼
if read stdin buf 0 1 = 0 then raise End_of_file▼
<code>ocaml unix.cma <yourfile.ml></code> interpreted<br/>
<code>ocamlc -o <progname> unix.cma <yourfile.ml></code> bytecode executable<br/>
<code>ocamlopt -o <progname> unix.cmxa <yourfile.ml></code> native executable
let buf = Bytes.create 1 in▼
let rec prompt () =▼
Here we define some helper functions that we'll use:
print_string "Prompt? [Y/N]: ";▼
<lang OCaml>let attrs = Unix.(tcgetattr stdin)
match getchar buf with▼
| 'n'|'N' -> ();▼
| 'y'|'Y' -> print_endline ": Ok."; prompt ();▼
| _ -> print_endline ": Invalid."; prompt ();▼
@@ if switch then { attrs with c_icanon = false } else attrs
let len = Unix.(read stdin) buf 0 1 in
Now the main program:
loop
@@ print_endline
let _ = try loop @@ prompt true with Exit | End_of_file -> prompt false</lang>
=={{header|Oforth}}==
|