To read and parse an integer from a bufio.Reader in Go, follow these steps:
import (
"bufio"
"fmt"
"os"
"strconv"
)
reader := bufio.NewReader(os.Stdin)
var intValue int
inputString, err := reader.ReadString('\n')
if err != nil {
// handle error
}
intValue, err = strconv.Atoi(inputString)
if err != nil {
// handle error
}
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.