Golang fmt.Scan()函数及示例

Golang fmt.Scan()函数及示例

Go 语言中, fmt 包实现了类似于 C 语言中的 printf() 和 scanf() 函数的格式化 I/O。而在 Go 语言中, fmt.Scan() 函数能够扫描输入的文本(给定标准输入中的文本),读取它们并将连续的以空格分隔的值存储到连续的参数中。此外,此函数在 fmt 包中定义。在使用这些功能之前,需要导入“fmt”包。

语法:

func Scan(a ...interface{}) (n int, err error)
Go

在此,”a …interface{}” 会接收每种给定文本类型。
返回值: 它返回成功扫描的项目数。

示例 1:

// Golang 程序演示 fmt.Scan() 函数用法

// 包含主包
package main

// 导入 fmt 包
import (
    "fmt"
)

// 调用主函数
func main() {

    // 声明一些变量
    var name string
    var alphabet_count int

    // 调用 Scan() 函数
    // 扫描并读取标准输入中给定的输入文本
    fmt.Scan(&name)
    fmt.Scan(&alphabet_count)

    // 输出给定文本
    fmt.Printf("单词 %s 包含 %d 个字母。",
        name, alphabet_count)

} 
Go

输入:

GFG 3
Go

输出:

单词 GFG 包含 3 个字母。
Go

示例 2:

// Golang 程序演示 fmt.Scan() 函数用法

// 包含主包
package main

// 导入 fmt 包
import (
    "fmt"
)

// 调用主函数
func main() {

    // 声明一些变量
    var name string
    var alphabet_count int
    var float_value float32
    var bool_value bool

    // 调用 Scan() 函数
    // 扫描并读取标准输入中给定的输入文本
    fmt.Scan(&name)
    fmt.Scan(&alphabet_count)
    fmt.Scan(&float_value)
    fmt.Scan(&bool_value)

    // 输出给定文本
    fmt.Printf("%s %d %g %t", name,
        alphabet_count, float_value, bool_value)

} 
Go

输入:

GeeksforGeeks 13 6.789 true
Go

输出:

GeeksforGeeks 13 6.789 true
Go

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册