dqba94619 2019-05-30 20:16
浏览 38
已采纳

如何在Go中处理控制台输入类型验证?

I'm trying to build a very basic console inputs for a program using a loop. However, when user inputs something else than an integer, the error message triggers as many times as there are characters in the input string (including newline).

I've tried Scan(), Scanln(), as well as bufio.NewReader() with string parsing, as well as using continue after Println(). All produce the same result.

var threads int

func main() {
    fmt.Println("Enter number of threads:")
    for {
        _, err := fmt.Scanln(&threads)
        if err != nil {
            fmt.Println("Enter a valid number")
        } else {
            break
        }
    }
}

User inputs:

asd

Expected result:

Program: Enter a valid number

Actual result:

Program: Enter a valid number

Program: Enter a valid number

Program: Enter a valid number

Program: Enter a valid number

  • 写回答

1条回答 默认 最新

  • douhuan3448 2019-05-30 21:34
    关注

    fmt.Scanln(&threads) throws an error because your first char is already not a valid int, thus there are sd still remaining in stdin buffer, this would be my explanation for additional three errors. To avoid this you could just read to string and then use int, err := strconv.Atoi(string) like in code below. Note hereby that fmt.Scan or fmt.Scanln split your userinput until the next space, which is probably not perfect for your usecase. Check out How to read input from console line for some insight in how to choose suiting your usecase.

    package main
    
    import (
        "fmt"
        "strconv"
    )
    
    func main() {
        var s string
        var i int
        fmt.Println("Enter number of threads:")
        for {
            _, err := fmt.Scan(&s)
            i, err = strconv.Atoi(s)
            if err != nil {
                fmt.Println("Enter a valid number")
            } else {
                fmt.Println("Got: " + strconv.Itoa(i))
                break
            }
        }
        //Todo
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥15 ensp路由器启动不了一直报#
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了