In the example, we will show you how to read input from a user with NewScanner in the Go language.
Go read input from user with NewScanner
The Scanner provides a convenient interface for reading data such as a file of newline-delimited lines of text.
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
names := make([]string, 0)
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print("Enter name: ")
scanner.Scan()
text := scanner.Text()
if len(text) != 0 {
fmt.Println(text)
names = append(names, text)
} else {
break
}
}
fmt.Println(names)
}
Output:
G:\GoLang\examples>go run go_example.go Enter name: John John Enter name: Tony Tony Enter name: Tom Tom Enter name: [John Tony Tom]
Note: The example allows to read multiple names from the user. Press enter without value to finish the program.
Comments
Post a Comment