reader.ReadString Does Not Strip Out Initial Delimiter
In an effort to create a program that greets users named Alice or Bob, a developer encountered an issue where even legitimate names triggered an unwelcome response. The program incorrectly denied entry to both Alice and Bob.
The Problem
The issue stems from the usage of reader.ReadString('\n') in the program. This function retrieves characters until a newline character is encountered. However, it does not automatically remove the delimiter from the returned string, leading to the inclusion of an additional newline in the user's input.
Solution
To resolve this issue, there are two possible approaches:
1. Trim the Newline
Use the strings.TrimSpace function to remove any leading or trailing whitespace from the input string before evaluating it. This effectively removes the newline character that caused the problem.
if aliceOrBob(strings.TrimSpace(text)) { fmt.Printf("Hello, ", text) }
2. Use ReadLine Instead of ReadString
Alternatively, the ReadLine function can be used instead of ReadString. ReadLine retrieves a line of text without including the newline character in the returned string.
text, _, _ := reader.ReadLine() if aliceOrBob(string(text)) { fmt.Printf("Hello, ", text) }
Explanation
The reason for using string(text) with ReadLine is that ReadLine returns a byte slice, while aliceOrBob requires a string argument.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3