3

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?

1
  • 1
    Did you try fmt.Fscan or fmt.Fscanf? What were your results? Commented Mar 15, 2014 at 7:59

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.