Question

Is there a way to scan a big.Int directly from the standard input in Go? Right now I'm doing this:

package main

import (
    "fmt"
    "math/big"
)

func main() {
    w := new(big.Int)
    var s string
    fmt.Scan(&s)
    fmt.Sscan(s, w)
    fmt.Println(w)
}

I also could have used .SetString. But, is there a way to Scan the big.Int directly from the standard input without scanning a string or an integer first?

Was it helpful?

Solution

For example,

package main

import (
    "fmt"
    "math/big"
)

func main() {
    w := new(big.Int)
    n, err := fmt.Scan(w)
    fmt.Println(n, err)
    fmt.Println(w.String())
}

Input (stdin):

295147905179352825857

Output (stdout):

1 <nil>
295147905179352825857

OTHER TIPS

As far as I know - no, there's no other way. In fact, what you've got is the default example they have for scanning big.Int in the documentation.

package main

import (
    "fmt"
    "log"
    "math/big"
)

func main() {
    // The Scan function is rarely used directly;
    // the fmt package recognizes it as an implementation of fmt.Scanner.
    i := new(big.Int)
    _, err := fmt.Sscan("18446744073709551617", i)
    if err != nil {
        log.Println("error scanning value:", err)
    } else {
        fmt.Println(i)
    }
}

You can see the relevant section here - http://golang.org/pkg/math/big/#Int.Scan

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top