How to scan a big.Int from standard input in Go

huangapple go评论81阅读模式
英文:

How to scan a big.Int from standard input in Go

问题

在Go语言中,可以直接从标准输入中扫描一个big.Int吗?目前我是这样做的:

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)
}

我也可以使用.SetString方法。但是,有没有一种方法可以直接从标准输入中扫描big.Int,而不是先扫描一个字符串或整数?

英文:

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

得分: 6

例如,

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())
}

输入(stdin):

295147905179352825857

输出(stdout):

1 <nil>
295147905179352825857
英文:

For example,

package main

import (
	&quot;fmt&quot;
	&quot;math/big&quot;
)

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 &lt;nil&gt;
295147905179352825857

答案2

得分: 1

据我所知,没有其他方法。实际上,你所看到的是在文档中用于扫描big.Int的默认示例。

package main

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

func main() {
	// Scan函数很少直接使用;
	// fmt包将其识别为fmt.Scanner的实现。
	i := new(big.Int)
	_, err := fmt.Sscan("18446744073709551617", i)
	if err != nil {
		log.Println("扫描值时出错:", err)
	} else {
		fmt.Println(i)
	}
}

你可以在这里查看相关部分 - http://golang.org/pkg/math/big/#Int.Scan

英文:

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 (
	&quot;fmt&quot;
	&quot;log&quot;
	&quot;math/big&quot;
)

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(&quot;18446744073709551617&quot;, i)
	if err != nil {
		log.Println(&quot;error scanning value:&quot;, err)
	} else {
		fmt.Println(i)
	}
}

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

huangapple
  • 本文由 发表于 2014年3月15日 14:55:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/22420612.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定