Go - Read Input From User With NewReader

1. Introduction

In Go, reading user input from the console can also be done using the bufio package, which provides a buffered reader that can read input line by line. This method is useful when you need to read multi-word strings or handle input more robustly. This blog post will demonstrate how to use bufio.NewReader to read user input.

Definition

bufio.NewReader creates a new buffered reader for reading from an io.Reader object, in this case, the standard input. The ReadString method of the bufio.Reader is then used to read input until a newline character is encountered.

2. Program Steps

1. Import the fmt and bufio packages, and the os package for standard input.

2. Create a new buffered reader using bufio.NewReader.

3. Prompt the user for input.

4. Use the ReadString method to read a line of input from the user.

5. Process and output the input to the user.

3. Code Program

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	// Step 2: Create a new buffered reader for standard input
	reader := bufio.NewReader(os.Stdin)

	// Step 3: Prompt the user for their name
	fmt.Println("Please enter your name:")

	// Step 4: Use ReadString to read the input until a newline
	name, err := reader.ReadString('\n')
	if err != nil {
		fmt.Fprintln(os.Stderr, "Error reading from stdin:", err)
		return
	}

	// Trim the newline character from the input
	name = name[:len(name)-1]

	// Step 5: Output the input to the user
	fmt.Printf("Hello, %s!\n", name)
}

Output:

Please enter your name:
Jane Doe
Hello, Jane Doe!

Explanation:

1. The package main indicates that the file belongs to the main package.

2. import statements are used to include the fmt, bufio, and os packages needed for input/output operations and access to the standard input.

3. bufio.NewReader(os.Stdin) is used to create a new buffered reader from the standard input.

4. fmt.Println is called to prompt the user to enter their name.

5. reader.ReadString('\n') reads the input from the user until a newline character is encountered.

6. An if statement checks for errors during input reading. If an error occurs, it prints the error message and returns from the main function.

7. The name string is trimmed to remove the newline character at the end, which is included by ReadString.

8. The fmt.Printf function then prints a personalized greeting using the user's input.

9. The output will greet the user with the name they entered, demonstrating successful reading and processing of user input.


Comments