Go语言 fmt.Fscanf()函数
fmt.Fscanf()语法
func Fscanf(r io.Reader, format string, a ...any) (n int, err error)
go源码对fmt.Fscanf()的介绍
Fscanf scans text read from r, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully parsed. Newlines in the input must match newlines in the format.
Golang标准库中fmt模块的Fscanf()方法,根据用于从指定的实现了io.Reader接口的输入源(如文件、字符串等对象)中读取格式化输入,读取到的结果将依次存储到指定的变量中(参数a指定)。
fmt.Fscanf()参数
参数 | 描述 |
---|---|
r | 实现了io.Reader接口的输入源; |
format | 格式字符串,用于指定了如何读取实现了io.Reader接口的输入源的数据; |
a | 一个或多个变量,用于存储读取的数据; |
fmt.Fscanf()方法返回值
n:成功读取并赋值的参数个数。err:在读取过程中可能遇到的error,若读取成功,err的值则为nil
fmt.Fscanf()方法实例代码
package main
import (
"fmt"
"strings"
)
func main() {
reader := strings.NewReader("Hello 123 World")
var x string
var y int
var z string
_, err := fmt.Fscanf(reader, "%s %d %s", &x, &y, &z)
if err == nil {
fmt.Println("x: ", x)
fmt.Println("y: ", y)
fmt.Println("z: ", z)
}
}
代码运行,得到输出:
x: Hello
y: 123
z: World
免责声明:内容仅供参考,不保证正确性。