dtjzpg5313 2012-12-12 10:47
浏览 116
已采纳

GOLang Scanf错误

When using Scanf twice the first time it gets the useres input but the second time it does not and returns out of the function. This is only a problem when running on Windows. When I run it on my Mac it works as expected first asking the uers for their username then their password. Below is the code in questions. I am not sure why it works fine on Mac but not on Windows. Any help in advance is appreciated. Thank you.

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
}
  • 写回答

1条回答 默认 最新

  • dongwei1263 2012-12-12 11:10
    关注

    Scanf is a bit finicky in that it uses spaces as a separator, and (at least for me) is rather unintuitive. Bufio does a good job of abstracting some of that:

    func credentials() (string, string) {
        reader := bufio.NewReader(os.Stdin)
    
        fmt.Print("Enter Username: ")
        username, _ := reader.ReadString('
    ')
    
        fmt.Print("Enter Password: ")
        password, _ := reader.ReadString('
    ')
    
        return strings.TrimSpace(username), strings.TrimSpace(password) // ReadString() leaves a trailing newline character
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 FPGA芯片60进制计数器
  • ¥15 前端js怎么实现word的.doc后缀文件在线预览
  • ¥20 macmin m 4连接iPad
  • ¥15 DBIF_REPO_SQL_ERROR
  • ¥15 根据历年月数据,用Stata预测未来六个月汇率
  • ¥15 DevEco studio开发工具 真机联调找不到手机设备
  • ¥15 请教前后端分离的问题
  • ¥100 冷钱包突然失效,急寻解决方案
  • ¥15 下载honeyd时报错 configure: error: you need to instal a more recent version of libdnet
  • ¥15 距离软磁铁一定距离的磁感应强度大小怎么求
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部