Always try to use the bufio.NewScanner for collecting input from the console. As others mentioned, there are multiple ways to do the job, but Scanner is originally intended to do the job. Dave Cheney explains why you should use Scanner instead of bufio.Reader's ReadLine.
https://twitter.com/davecheney/status/604837853344989184?lang=en
Here is the code snippet answer for your question
package main
import (
"bufio"
"fmt"
"os"
)
/*
Three ways of taking input
1. fmt.Scanln(&input)
2. reader.ReadString()
3. scanner.Scan()
Here we recommend using bufio.NewScanner
*/
func main() {
// To create dynamic array
arr := make([]string, 0)
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print("Enter Text: ")
// Scans a line from Stdin(Console)
scanner.Scan()
// Holds the string that scanned
text := scanner.Text()
if len(text) != 0 {
fmt.Println(text)
arr = append(arr, text)
} else {
break
}
}
// Use collected inputs
fmt.Println(arr)
}
If you don't want to programmatically collect the inputs, just add these lines
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
text := scanner.Text()
fmt.Println(text)
The output of above program will be:
Enter Text: Bob
Bob
Enter Text: Alice
Alice
Enter Text:
[Bob Alice]
The above program collects the user input and saves them to an array. We can also break that flow with a special character. Scanner provides API for advanced usage like splitting using a custom function, etc., scanning different types of I/O streams (standard Stdin
, String
), etc.
bufio
buffering of any reader (e.g.bufio.NewReader(os.Stdin)
) with direct reads from the underlining reader (e.g.fmt.Scanln(x)
directly reads fromos.Stdin
). Buffering may read arbitrarily far ahead. (In this specific case the later should befmt.Fscanln(reader,x)
to read from the same buffer). – Dave Cfmt.Sscanln
works, it becomes "%v" after running – Beeno Tung