Console I/O
suggest changeWhen writing command-line programs, you can read user input from os.Stdin using any function that accepts io.Reader.
fmt.Scanf to read from stdio
The most convenient way is fmt.Scanf, which reads text using format verbs similar to fmt.Printf.
Here is how to read a string and an integer from standard input:
fmt.Print("What is your name?\n")
var name string
if n, err := fmt.Scanf("%s", &name); err != nil {
fmt.Printf("fmt.Scanf failed with '%s'\n", err)
} else {
fmt.Printf("fmt.Scanf scanned %d item(s) and set name to '%s'\n", n, name)
}
fmt.Print("What is your age?\n")
var age int
if n, err := fmt.Scanf("%d", &age); err != nil {
fmt.Printf("fmt.Scanf failed with '%s'\n", err)
} else {
fmt.Printf("fmt.Scanf scanned %d item(s) and set age to '%d'\n", n, age)
}
What is your name?
fmt.Scanf failed with 'EOF'
What is your age?
fmt.Scanf failed with 'EOF'
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 the number of items it successfully parsed (which can be fewer than the number of verbs).
To read from arbitrary io.Reader use fmt.Fscanf.
fmt.Scanln to read a line from stdin
To read a full line (until a newline or io.EOF), use fmt.Scanln:
var line string
fmt.Scanln(&line)
fmt.Printf("Entered line: '%s'\n", line)
Entered line: ''
bufio.Reader to read a line from stdin
You can also use bufio.Reader:
reader := bufio.NewReader(os.Stdin)
if line, err := reader.ReadString('\n'); err != nil {
fmt.Printf("ReadString failed with '%s'\n", err)
} else {
fmt.Printf("Entered line: '%s'\n", line)
}
ReadString failed with 'EOF'
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).
bufio.Scanner to read a line from stdin
You can also use bufio.Scanner to read lines from stdin:
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
fmt.Printf("Entered line: '%s'\n", line)
}
scanner.Text() returns the line without its newline. The default split function accepts both \n and \r\n. For other chunking rules, set a split function with Scanner.Split.