dow72046
dow72046
2011-11-16 19:23

多个输入(fmt.Scanln)

已采纳

Why does this doesn't work, or how to get multiple input with fmt.Scanln?

EDIT: If I insert more then one word then I get the Error "Scan: expected newline", anything I can do about this?

    var username string
    print("Username: ")
    _, err := fmt.Scanln(&username)
    if err != nil {
            fmt.Println("Error: ", err)
    }

    var password string
    print("Password: ")
    _, err := fmt.Scanln(&password)
    if err != nil {
            fmt.Println("Error: ", err)
    }

    var status string
    print("Status: ")
    _, err := fmt.Scanln(&status)
    if err != nil {
            fmt.Println("Error: ", err)
    }

    fmt.Println(username, password, status)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • duanbin4847 duanbin4847 10年前

    You are re-declaring the err variable multiple times in the same scope. The compiler error should have made that clear. The following will work:

    var err error
    var username string
    
    print("Username: ")
    _, err = fmt.Scanln(&username)
    if err != nil {
        fmt.Println("Error: ", err)
    }
    
    var password string
    print("Password: ")
    _, err = fmt.Scanln(&password)
    if err != nil {
        fmt.Println("Error: ", err)
    }
    
    var status string
    print("Status: ")
    _, err = fmt.Scanln(&status)
    if err != nil {
        fmt.Println("Error: ", err)
    }
    
    fmt.Println(username, password, status)
    return
    
    点赞 评论 复制链接分享

相关推荐