为什么 fmt.Fscan 不能将小写字母读取为字节值?

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

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

输出结果是:

为什么 fmt.Fscan 不能将小写字母读取为字节值?

我将输入从 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)
}

output is:
为什么 fmt.Fscan 不能将小写字母读取为字节值?

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.ReaderRead方法。

英文:

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.

huangapple
  • 本文由 发表于 2023年3月12日 23:49:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75714325.html
匿名

发表评论

匿名网友

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

确定