Home >Backend Development >Golang >Why Does Go's `bufio.Reader.ReadString` Preserve Leading Delimiters, and How Can I Avoid This Issue?
Reader.ReadString May Preserve Leading Delimiters
In Go, bufio.Reader.ReadString behavior can differ when parsing input. Consider the following scenario:
import ( "bufio" "fmt" "os" ) func main() { reader := bufio.NewReader(os.Stdin) fmt.Print("Who are you? Enter your name: ") text, _ := reader.ReadString('\n') if text == "Alice" || text == "Bob" { fmt.Printf("Hello, ", text) } else { fmt.Printf("You're not allowed in here!") } }
Here, ReadString is used to read user input and expects names terminated by a newline character. However, when the entered name matches "Alice" or "Bob," the program erroneously denies access.
Cause and Solution
This issue arises because ReadString preserves leading occurrences of the delimiter (in this case, 'n'). When a name like "Alice" is entered, the string stored in text includes both "Alice" and a trailing newline. This extra newline character prevents the string comparison from matching the expected value.
To resolve this issue, consider the following approaches:
The above is the detailed content of Why Does Go's `bufio.Reader.ReadString` Preserve Leading Delimiters, and How Can I Avoid This Issue?. For more information, please follow other related articles on the PHP Chinese website!