In this tutorial, we will learn different ways to read input from the User or Console in the Golang program.
Go ( Golang) - Read Input from User or Console
- Go - read input with Scanf
- Go - read input from the user with NewReader
- Go - read input from the user with NewScanner
Go - read input with Scanf
The Scanf function scans text read from standard input, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully scanned.
Let's create a file named go_example.go and add the following content to it:
package main
import "fmt"
func main() {
var name string
fmt.Print("Enter your name: ")
fmt.Scanf("%s", &name)
fmt.Println("Hello", name)
}
Output:
G:\GoLang\examples>go run go_example.go Enter your name: John Hello John
The example prompts the user to enter his name.
Go - read input from the user with NewReader
The program reads a name from the input using bufio.NewReader.
Let's create a file named go_example.go and add the following content to it:
package main
import (
"os"
"bufio"
"fmt"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your name: ")
name, _ := reader.ReadString('\n')
fmt.Printf("Hello %s\n", name)
}
Output:
G:\GoLang\examples>go run go_example.go Enter your name: John Hello John
Go - read input from the user with NewScanner
The Scanner provides a convenient interface for reading data such as a file of newline-delimited lines of text.
Below example of read input from a user with NewScanner in the Go language.
Let's create a file named go_example.go and add the following content to it:
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.
Golang Related Tutorials
- Go (Golang) Functions with Examples
- Go (Golang) Operators with Examples
- Go ( Golang) - Read Input from User or Console
- Go (Golang) Read and Write File Example Tutorial
- Go (Golang) Array Tutorial
- Go (Golang) Slices Tutorial with Examples
- Go (Golang) Maps Tutorial with Examples
- Go (Golang) Structs Tutorial with Examples
Comments
Post a Comment
Leave Comment