In Go, you can read keyboard input from the console using the bufio
package and the os.Stdin
file object. Here’s an example that demonstrates how to read input from the keyboard:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter your name: ")
name, _ := reader.ReadString('\n')
fmt.Print("Enter your age: ")
var age int
_, err := fmt.Scanln(&age)
if err != nil {
fmt.Println("Invalid input for age.")
return
}
fmt.Printf("Hello, %s! You are %d years old.\n", name, age)
}
In the above example, we first import the necessary packages: bufio
, fmt
, and os
.
Inside the main
function, we create a bufio.Reader
object called reader
that reads from os.Stdin
(standard input).
We prompt the user to enter their name by using fmt.Print
to display a message. Then, we use reader.ReadString('\n')
to read the input until a newline character (‘\n’) is encountered. The entered name is stored in the name
variable.
Next, we prompt the user to enter their age. We use fmt.Scanln(&age)
to read the input as an integer and store it in the age
variable. If the input is not a valid integer, an error will occur.
Finally, we print a greeting message using the entered name and age.
Note: The ReadString('\n')
function includes the newline character in the string, so you may need to trim it using the strings.TrimSpace()
function from the strings
package if you want to remove leading or trailing whitespace.
To run this program, you can compile and execute it as you would with any Go program. After running it, you can enter your name and age in the console, and the program will display a greeting message with the entered values.