douyan8070 2018-01-07 07:10
浏览 58
已采纳

快速输入方法,用空格分隔[Golang]

I'm trying to take fast input through scanner.Bytes and I'm it converting to int. The problem is : input provided is single line spaced elements ( like an array ) and scanner.Bytes reads it as a whole and converts it into int. How can I use a Splitfunction on the bytes read!

func main()  {
    scanner := bufio.NewScanner(os.Stdin)
    var t int
    fmt.Scanf("%d", &t)

    for o := 0; o < t; o++ {
        scanner.Scan()
        //scanner.Split(bufio.ScanWords())
        val := toInt(scanner.Bytes())
        fmt.Println(val)
    }
}

func toInt(buf []byte) (n int) {
    for _, v := range buf {
        n = n*10 + int(v-'0')
    }
    return
}
  • 写回答

3条回答 默认 最新

  • dongzhenbi8919 2018-01-07 21:01
    关注

    why not just try something like

    func main()  {
        scanner := bufio.NewScanner(os.Stdin)
    
        for scanner.Scan() {
            val, err := strconv.Atoi(scanner.Text())
            if err != nil {
                log.Fatal(err)
            }
            fmt.Println(val)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料