英文:
Golang: Read ints from stdin until EOF while reporting format errors
问题
nums := make([]int, 0)
{
var d int
for {
_, err := fmt.Scan(&d)
if err != nil {
break
}
nums = append(nums, d)
}
}
这段代码用于从标准输入中读取整数。但是如果标准输入看起来像 1 2 3 f4 5
,nums
最终会变成 [1 2 3]
,而不报告任何错误。
如何处理这种情况最好?(即,我希望从 fmt.Scan
中获得 EOF 时,循环会静默退出,但其他所有错误都应该报告)。
编辑:我只需要 io.EOF
-- 我在 http://golang.org/pkg/fmt/ 上没有找到这个文档
nums := make([]int, 0)
{
var d int
for {
_, err := fmt.Scan(&d)
if err != nil {
if err != io.EOF {
log.Fatal(err)
}
break
}
nums = append(nums, d)
}
}
英文:
nums := make([]int, 0)
{
var d int
for {
_, err := fmt.Scan(&d)
if err != nil {
break
}
nums = append(nums, d)
}
}
This works to read in ints from stdin. But if stdin looks like 1 2 3 f4 5
, nums
will end up being [1 2 3]
without reporting any error.
What's the best way of handling this? (Ie, I want EOF from fmt.Scan
to silently exit the loop, but all other errors should be reported).
edit: io.EOF
was all I needed -- I hadn't found that documented at http://golang.org/pkg/fmt/
nums := make([]int, 0)
{
var d int
for {
_, err := fmt.Scan(&d)
if err != nil {
if err != io.EOF {
log.Fatal(err)
}
break
}
nums = append(nums, d)
}
}
答案1
得分: 16
你可以这样做-当你得到一个错误的数字时,读取下一个以空格分隔的内容。设置一个标志或在出现错误时保留一个错误列表,在最后报告这些错误。
package main
import (
"bytes"
"fmt"
"io"
)
func main() {
in := bytes.NewBufferString("1 2 3 f4 5")
nums := make([]int, 0)
var d int
for i := 0; i < 10; i++ {
_, err := fmt.Fscan(in, &d)
if err == io.EOF {
break
}
if err != nil {
var s string
_, err := fmt.Fscan(in, &s)
if err != nil {
break
}
fmt.Printf("跳过错误的数字:%q\n", s)
} else {
nums = append(nums, d)
}
}
fmt.Printf("nums = %v\n", nums)
}
输出结果为:
跳过错误的数字:"f4"
nums = [1 2 3 5]
英文:
You could do it like this - when you get a bad number, read the next space separated thing. Set a flag or on an error or keep a list of the errors to report at the end.
package main
import (
"bytes"
"fmt"
"io"
)
func main() {
in := bytes.NewBufferString("1 2 3 f4 5")
nums := make([]int, 0)
var d int
for i := 0; i < 10; i++ {
_, err := fmt.Fscan(in, &d)
if err == io.EOF {
break
}
if err != nil {
var s string
_, err := fmt.Fscan(in, &s)
if err != nil {
break
}
fmt.Printf("Skipping bad number: %q\n", s)
} else {
nums = append(nums, d)
}
}
fmt.Printf("nums = %v\n", nums)
}
Which prints
Skipping bad number: "f4"
nums = [1 2 3 5]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论