go fmt.Scan Scanf Scanln的一个小问题
bug记录
Scan,Scanf,Scanln的一个问题
go的fmt.Scan在使用中的一个小问题,如下:
for{ fmt.Println("请选择:1-剪刀 2-石头 3-布 ,0-不玩了") count, err := fmt.Scan(&people) if err != nil { fmt.Println(err) fmt.Printf("count:%d ", count) fmt.Println("您的输入有误,请重新输入") continue } //其他逻辑代码 }
这段代码在我正常输入数字的情况下是没有问题的,可以正常获取数值,但是输入非数字的情况下,就会出现,“输入多少个字符,if块里的错误代码就会执行多少遍的情况。”
请选择:1-剪刀 2-石头 3-布 ,0-不玩了 1 您出的是[剪刀],电脑出的是[布] ***********您输了!!*********** 请选择:1-剪刀 2-石头 3-布 ,0-不玩了 ab expected integer count:0您的输入有误,请重新输入 请选择:1-剪刀 2-石头 3-布 ,0-不玩了 expected integer count:0您的输入有误,请重新输入 请选择:1-剪刀 2-石头 3-布 ,0-不玩了 abc expected integer count:0您的输入有误,请重新输入 请选择:1-剪刀 2-石头 3-布 ,0-不玩了 expected integer count:0您的输入有误,请重新输入 请选择:1-剪刀 2-石头 3-布 ,0-不玩了 expected integer count:0您的输入有误,请重新输入 请选择:1-剪刀 2-石头 3-布 ,0-不玩了
感觉是continue之后fmt.Scan()函数并没有重新从标准输入里读取,而是读取到了第一次输入的整个字符串中的下一个字符。 更换使用Scanln或者Scanf后,问题同样存在。
最后采用bufio.NewReader才彻底解决。
for{ fmt.Println("请选择:1-剪刀 2-石头 3-布 ,0-不玩了") stdin := bufio.NewReader(os.Stdin) count, err := fmt.Fscan(stdin, &people) stdin.ReadString( ) if err != nil { fmt.Println(err) fmt.Printf("count:%d ", count) fmt.Println("您的输入有误,请重新输入") continue } //其他逻辑代码 }