$search fmt.Fscanf
When writing command-line programs, you can read user input from os.Stdin
using any function that accepts io.Reader
.
Most convenient way is to use fmt.Scanf
which is a mirror image of fmt.Printf
.
Here's how to read a string and an integer from the console (standard input)
https://codeeval.dev/gist/5579a4213b5a8b72a4e4a2cc29f3d254
fmt.Scanf
reads input from os.Stdin
and tries to set passed variables based on provided format.
A space and newline are considered value separators.
It returns number of successfully parsed items (in case it only matched first few variables).
To read from arbitrary io.Reader
use fmt.Fscanf
.
To read a full line (until newline or io.EOF
, use fmt.Scanln
:
https://codeeval.dev/gist/285a79ba0ed0a805b16536d11efd7454
You can also use bufio.Reader
:
https://codeeval.dev/gist/0d65a1c55c361c4a74166b623f28dd63
ReadString
reads from the reader until it reads a given character. We specified newline \\n
character so it'll read a full line.
The value returned by ReadString
includes the terminating character (\\n
) so often you'll want to strip it with e.g. strings.TrimSpace
.
Character \\n
is a line terminator on Unix. On Windows it's more common to see \\r\\n
as a line terminator. If you expect to be run on Windows, make sure to handle this (e.g. by trimming \\r
character from returned string).