为什么第二个 scanf 被跳过?

Kad*_*ams 1 go

我决定看看 Go,但目前我陷入了困境。在此程序中,我要求用户选择选项 1 或 2。如果选择选项 1,我希望 ReadAppList 函数询问用户的姓氏。

似乎第二个 scanf 被跳过并且不允许用户输入姓氏。它只读取第一个用户输入吗?

package main

import (
    "fmt"
)


// Main function that runs on startup
func main() {

    fmt.Println("\n1. Search Last Name ")
    fmt.Println("\n2. Exit ")
    fmt.Println("\nPick an option: ")
    var userAnswer int
    fmt.Scanf("%d", &userAnswer)

    if userAnswer == 1 {

        ReadAppsList()

    } else if userAnswer == 2 {

        fmt.Println("\nGoodbye.")

    } else {

        fmt.Println("\nThat is not a valid choice.")

    }
}

func ReadAppsList() {

    fmt.Println("\nType your LastName of the person you want to look up: ")
    var lastName string
    fmt.Scanf("%s", &lastName)
    fmt.Sprintf("You typed %s", lastName)
}
Run Code Online (Sandbox Code Playgroud)

Ash*_*deh 5

这是因为第一次 scanf 没有消耗额外的换行符。
将你的 scanf 更改为此fmt.Scanf("%d\n", &userAnswer)