Best way to make a racket entry?

What is the best way to read input from stdin in a racket?

In particular, I would like something like cin from C ++ or scanf from c, where I specify the types of things I want to read and they are returned.

+6
source share
3 answers

You can do almost anything you want at a low level, I would suggest (read-line) and (read-bytes). For higher level processing (e.g. scanf), I would suggest regexp-match in the input. For instance,

 (regexp-match #px" *([0-9]+)" (current-input-port)) 
+7
source

read-line easy. To be portable over Unix and Windows, an additional option is required.

 (read-line (current-input-port) 'any) 

Return and line feed characters are detected after conversions that are automatically performed when reading a file in text mode. For example, reading a file in text mode on Windows automatically changes return-linefeed to line feed. Thus, when a file is opened in text mode, line-to-line is usually the corresponding line of read mode.

So, "anyone should be portable if the input port is not a file (standard input).

Testing program:

 #lang racket (let loop () (display "Input: ") (define a (read-line (current-input-port) 'any)) (printf "input: ~a, length: ~a, last character: ~a\n" a (string-length a) (char->integer (string-ref a (- (string-length a) 1)))) (loop)) 

On Windows, replace (read-line (current-input-port) 'any) with (read-line) and see what happens.

+5
source

I would use the read procedure for the general case. If the data type used is known in advance, use read-char , read-string , read-bytes .

Also, see this implementation for reading formatted input - a scanf in a schema.

+2
source

Source: https://habr.com/ru/post/901423/


All Articles