Home > Backend Development > Golang > Why Does Scanf Fail on Second Input in Go on Windows?

Why Does Scanf Fail on Second Input in Go on Windows?

DDD
Release: 2024-10-26 11:14:29
Original
636 people have browsed it

Why Does Scanf Fail on Second Input in Go on Windows?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template