📜  Golang 中的 fmt.Fscanln()函数示例

📅  最后修改于: 2021-10-24 12:58:25             🧑  作者: Mango

在 Go 语言中, fmt包使用类似于 C 的 printf() 和 scanf()函数的函数来实现格式化的 I/O。 Go 语言中的fmt.Fscanln()函数扫描指定的文本,从 r 读取,然后将连续的空格分隔值存储到连续的参数中。此函数在换行符处停止扫描,在最后一项之后,必须有一个换行符或 EOF。而且,这个函数是在 fmt 包下定义的。在这里,您需要导入“fmt”包才能使用这些功能。

句法:

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

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

  • r io.Reader:该参数包含扫描的指定文本。
  • a …interface{}:这些参数接受每个指定的元素。

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

示例 1:

// Golang program to illustrate the usage of
// fmt.Fscanln() function
  
// Including the main package
package main
  
// Importing fmt, io and strings
import (
    "fmt"
    "io"
    "strings"
)
  
// Calling main
func main() {
  
    // Declaring list of strings,
    // integers and float value
    s := `gfg 9`
  
    // Calling NewReader() function for
    // reading each elements of the list
    // and then it place it into "r"
    r := strings.NewReader(s)
  
    // Declaring different types of variables
    var a string
    var b int
  
    for {
  
        // Calling Fscanln() function
        n, err := fmt.Fscanln(r, &a, &b)
  
        // Checking returned error is
        // end of the line (EOF) or not
        if err == io.EOF {
            break
        }
  
        // Checking if there is any error
        if err != nil {
            panic(err)
        }
  
        // Printing the number of items successfully
        // scanned and each elements too
        fmt.Printf("%d: %s, %d", n, a, b)
    }
}

输出:

2: gfg, 9

示例 2:

// Golang program to illustrate the usage of
// fmt.Fscanln() function
  
// Including the main package
package main
  
// Importing fmt, io and strings
import (
    "fmt"
    "io"
    "strings"
)
  
// Calling main
func main() {
  
    // Declaring list of strings,
    // integers and float value
    s := `gfg 9 true 5.78`
  
    // Calling NewReader() function for
    // reading each elements of the list
    // and then it place it into "r"
    r := strings.NewReader(s)
  
    // Declaring different types of variables
    var a string
    var b int
    var c bool
    var d float32
  
    for {
  
        // Calling Fscanln() function
        n, err := fmt.Fscanln(r, &a, &b, &c, &d)
  
        // Checking returned error is
        // end of the line (EOF) or not
        if err == io.EOF {
            break
        }
  
        // Checking if there is any error
        if err != nil {
            panic(err)
        }
  
        // Printing the number of items successfully
        // scanned and each elements too
        fmt.Printf("%d: %s, %d, %t, %g", n, a, b, c, d)
    }
}

输出:

4: gfg, 9, true, 5.78