How to read and parse an integer from a bufio.Reader in Go?

To read and parse an integer from a bufio.Reader in Go, follow these steps:

  1. Import the necessary packages:
import ( "bufio" "fmt" "os" "strconv" )
  1. Create a bufio.Reader to read the input from the desired source (e.g., os.Stdin) and a variable to store the parsed integer:
reader := bufio.NewReader(os.Stdin) var intValue int
  1. Read a string from the reader:
inputString, err := reader.ReadString('\n') if err != nil { // handle error }
  1. Parse the string to an integer using the strconv.Atoi() function:
intValue, err = strconv.Atoi(inputString) if err != nil { // handle error }
  1. Now, you can use the parsed integer as needed:
fmt.Println("Parsed integer:", intValue)

Below is the complete example code:

package main import ( "bufio" "fmt" "os" "strconv" ) func main() { reader := bufio.NewReader(os.Stdin) var intValue int fmt.Print("Enter an integer: ") inputString, err := reader.ReadString('\n') if err != nil { fmt.Println("Error reading input:", err) return } intValue, err = strconv.Atoi(inputString) if err != nil { fmt.Println("Error parsing integer:", err) return } fmt.Println("Parsed integer:", intValue) }

With this code, you can prompt the user to enter an integer and parse it from the standard input. Note that you may need additional error handling depending on your specific use case.