Reading an integer from standard input

前端 未结 5 1960
轻奢々
轻奢々 2020-12-12 18:58

How do I use the fmt.Scanf function in Go to get an integer input from the standard input?

If this can\'t be done using fmt.Scanf, what\'s

5条回答
  •  被撕碎了的回忆
    2020-12-12 19:10

    Here is my "Fast IO" method for reading positive integers. It could be improved with bitshifts and laying out memory in advance.

    package main
    
    import (
        "io/ioutil"
        "bufio"
        "os"
        "strconv"
    )
    
    
    func main() {
        out := bufio.NewWriter(os.Stdout)
        ints := getInts()
        var T int64
        T, ints = ints[0], ints[1:]
        ..
        out.WriteString(strconv.Itoa(my_num) + "\n")
        out.Flush()
        }
    }
    
    func getInts() []int64 {
        //assumes POSITIVE INTEGERS. Check v for '-' if you have negative.
        var buf []byte
        buf, _ = ioutil.ReadAll(os.Stdin)
        var ints []int64
        num := int64(0)
        found := false
        for _, v := range buf {
            if '0' <= v && v <= '9' {
                num = 10*num + int64(v - '0') //could use bitshifting here.
                found = true
            } else if found {
                ints = append(ints, num)
                found = false
                num = 0
            }
        }
        if found {
            ints = append(ints, num)
            found = false
            num = 0
        }
        return ints
    }
    

提交回复
热议问题