Error Using Scanf in GOLang on Windows
The Scanf function in GOLang can present an issue when attempting to obtain user input twice. The first input is retrieved successfully, but the function terminates abruptly during the second attempt on Windows systems. This behavior does not occur on macOS.
<code class="go">func credentials() (string, string) { var username string var password string fmt.Print("Enter Username: ") fmt.Scanf("%s", &username) fmt.Print("Enter Password: ") fmt.Scanf("%s", &password) return username, password }</code>
Solution:
Scanf is peculiar in its use of spaces as separators, making it somewhat challenging to use. Bufio offers a superior alternative that simplifies the process.
<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) // Remove trailing newline character }</code>
This modified code addresses the issue and functions seamlessly on both Windows and macOS.
The above is the detailed content of Why Does Scanf Fail on Second Input in Go on Windows?. For more information, please follow other related articles on the PHP Chinese website!