Go语言 fmt.Scanf()方法

fmt.Scanf()语法

func Scanf(format string, a ...any) (n int, err error)

go源码对fmt.Scanf()的介绍

Scanf scans text read from standard input, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully scanned. If that is less than the number of arguments, err will report why. Newlines in the input must match newlines in the format. The one exception: the verb %c always scans the next rune in the input, even if it is a space (or tab etc.) or newline.

Golang标准库中fmt模块的Scanf()方法,根据参数format指定的格式字符串从标准输入读取数据,并将读取到的数据依次存储在提供的变量中(参数a指定的变量)。

fmt.Scanf()参数

参数描述
format格式字符串,用于指定了如何读取输入数据;
a一个或多个变量,用于存储读取的数据,用法可参考下方的实例代码;

fmt.Scanf()方法返回值

n:成功读取并赋值的参数个数,如果不使用,可以使用“_”来取代,具体可参考下方实例中的用法。err:在读取过程中可能遇到的任何error,如果读取成功则为nil

fmt.Scanf()方法实例代码

package main

import (
	"fmt"
)

func main() {
	var x int
	var y int
	fmt.Print("输入两个数字,使用空格隔开,程序将自动求和:")
	_, e := fmt.Scanf("%d %d", &x, &y)
	if e == nil {
		z := x + y
		fmt.Printf("你输入的数字的和为:%d", z)
	}

}

代码运行,得到输出(及相关的输入):

输入两个数字,使用空格隔开,程序将自动求和:1 2
你输入的数字的和为:3

免责声明:内容仅供参考,不保证正确性。


全栈后端 / go语法 :













Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.