英文:
why fmt.Fscan can't read lowcase letter to a byte value?
问题
代码如下:
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
reader := bufio.NewReader(strings.NewReader("a" +
"2" +
"3"))
var a byte
fmt.Fscan(reader, &a)
fmt.Println(a)
}
它的输出结果是 0
。
但是,如果我将输入更改为以下内容:
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
reader := bufio.NewReader(strings.NewReader("1" +
"2" +
"3"))
var a byte
fmt.Fscan(reader, &a)
fmt.Println(a)
}
输出结果是:
我将输入从 a\n2\n3
更改为 1\n2\n3
。导致 a
无法被扫描到一个值中。
我不知道为什么,谁能解释给我?非常感谢。
英文:
code like this :
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
reader := bufio.NewReader(strings.NewReader("a" +
"2" +
"3"))
var a byte
fmt.Fscan(reader, &a)
fmt.Println(a)
}
it will output 0
but if I change input to this :
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
reader := bufio.NewReader(strings.NewReader("1" +
"2" +
"3"))
var a byte
fmt.Fscan(reader, &a)
fmt.Println(a)
}
I change input from a\n2\n3
to 1\n2\n3
. caused a
can't scan into a value.
I don't konw why, who can explain it to me? thanks a lot.
答案1
得分: 4
fmt.Fscan
检查输入参数的类型以确定其解析行为。在这种情况下,唯一的输入参数是byte
类型,它是uint8
的内置类型别名(链接),这导致fmt.Fscan
尝试从输入的io.Reader
(链接)中解析无符号数字。123
可以成功解析为无符号数字,而a23
则不行。fmt.Fscan
有返回值,包括成功扫描的项目数和一个错误,你正在忽略这些返回值。如果你打印出错误信息,就可以更容易地发现问题。
如果你的目标是逐字节读取一些输入,你可以直接使用io.Reader
的Read
方法。
英文:
fmt.Fscan
examines the types of the input arguments to drive its parsing behavior. In this case, the only input argument is of type byte
, which is a built-in type alias of uint8
(link), which causes fmt.Fscan
to try to parse an unsigned number out of the input io.Reader
(link). 123
can successfully be parsed as an unsigned number whereas a23
cannot. fmt.Fscan
does have return values of the number of items successfully scanned and an error, which you're discarding. If you print the error out, that'll make it easier to spot the problem.
If your goal is to read some input byte by byte, you can use the Read
off of the io.Reader
directly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论