当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Golang fmt.Fscanln()用法及代码示例


在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



相关用法


注:本文由纯净天空筛选整理自Kanchan_Ray大神的英文原创作品 fmt.Fscanln() Function in Golang With Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。