Golang fmt.Fscan() 函数及示例

Golang fmt.Fscan() 函数及示例

Go 语言中,fmt 包通过类似于 C 语言的 printf() 和 scanf() 函数实现格式化的 I/O。在 Go 语言中, fmt.Fscan() 函数扫描指定的文本(从 r 中读取),然后将连续的空格分隔的值存储到连续的参数中。这里,换行符也视为一个空格。此外,此函数定义在 fmt 包中。在使用这些函数之前,需要导入 “fmt” 包。

语法:

func Fscan(r io.Reader, a ...interface{}) (n int, err error)

参数: 此函数接受两个参数,如下所示:

  • r io.Reader: 此参数包含要扫描的指定文本。
  • a …interface{}: 此参数接收指定文本的每个类型。

返回: 它返回成功扫描的项数。

示例 1:

// Golang program to illustrate the usage of
// fmt.Fscan() function
  
// Including the main package
package main
  
// Importing fmt, io and strings
import (
    "fmt"
    "os"
    "strings"
)
  
// Calling main
func main() {
  
        // Declaring some type of variables
    var (
        i int
        b bool
        s string
    )
      
    // Calling the NewReader() function to
    // specify some type of texts.
    // variable "r" contains the scanned texts
    r := strings.NewReader("10 false GFG")
      
    // Calling the Fscan() function to receive 
    // the scanned texts
    n, err := fmt.Fscan(r, &i, &b, &s)
      
    // If the above function returns an error then
    // below statement will be executed
    if err != nil {
        fmt.Fprintf(os.Stderr, "Fscanf: %v\n", err)
    }
      
    // Printing each type of scanned texts
    fmt.Println(i, b, s)
      
    // It returns the number of items 
    // successfully scanned
    fmt.Println(n)
} 

输出:

10 false GFG
3

示例 2:

// Golang program to illustrate the usage of
// fmt.Fscan() function
  
// Including the main package
package main
  
// Importing fmt, io and strings
import (
    "fmt"
    "os"
    "strings"
)
  
// Calling main
func main() {
  
        // Declaring some type of variables
    var (
        i int
        b bool
        s string
        f float32
    )
      
    // Calling the NewReader() function to
    // specify some type of texts.
    // variable "r" contains the scanned texts
    r := strings.NewReader("46 true 3.4 GeeksforGeeks")
      
    // Calling the Fscan() function to receive 
    // the scanned texts
    n, err := fmt.Fscan(r, &i, &b, &f, &s)
      
    // If the above function returns an error then
    // below statement will be executed
    if err != nil {
        fmt.Fprintf(os.Stderr, "Fscanf: %v\n", err)
    }
      
    // Printing each type of scanned texts
    fmt.Println(i, b, f, s)
      
    // It returns the number of items 
    // successfully scanned
    fmt.Println(n)
} 

输出:

46 true 3.4 GeeksforGeeks
4

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程