英文:
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 (
"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
答案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 (
"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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论