GOLang Scanf Error on Windows
In GOLang, the Scanf function is known to encounter an error when used consecutively on Windows systems. While the first usage of Scanf successfully retrieves user input, subsequent attempts fail, leading to an abrupt exit from the function.
To rectify this issue, it is advisable to utilize the Bufio package, which offers a more refined approach. Bufio abstracts certain complexities of Scanf, such as its reliance on spaces as separators. Here's an example of how to use Bufio to gracefully gather credentials:
<code class="go">func credentials() (string, string) { reader := bufio.NewReader(os.Stdin) fmt.Print("Enter Username: ") username, _ := reader.ReadString('\n') fmt.Print("Enter Password: ") password, _ := reader.ReadString('\n') return strings.TrimSpace(username), strings.TrimSpace(password) // ReadString() leaves a trailing newline character }</code>
By using ReadString to retrieve user input, the Bufio package eliminates the issue experienced with Scanf on Windows. It also handles the trailing newline character automatically, ensuring clean and consistent data capture.
The above is the detailed content of Why is Scanf Failing on Windows in Golang?. For more information, please follow other related articles on the PHP Chinese website!