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


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

在Go语言中,fmt软件包使用与C的printf()和scanf()函数相似的函数来实现格式化的I /O。 Go语言中的fmt.Sscan()函数扫描指定的文本,并将连续的以空格分隔的文本存储到连续的参数中。此外,该函数在fmt包下定义。在这里,您需要导入“fmt”包才能使用这些函数。

用法:

func Sscan(str string, a ...interface{}) (n int, err error)

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

  • str string:此参数包含将要扫描的指定文本。
  • a …interface{}:此参数接收每个文本。

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

范例1:



// Golang program to illustrate the usage of 
// fmt.Sscan() function 
  
// Including the main package 
package main 
  
// Importing fmt 
import ( 
    "fmt"
) 
  
// Calling main 
func main() { 
  
    // Declaring two variables 
    var name string 
    var alphabet_count int
  
    // Calling the Sscan() function which 
    // returns the number of elements 
    // successfully scanned and error if 
    // it persists 
    n, err:= fmt.Sscan("GFG 3", &name, &alphabet_count) 
  
    // Below statements get executed if there is any error 
    if err != nil { 
        panic(err) 
    } 
  
    // Printing the number of elements and each elements also 
    fmt.Printf("%d:%s, %d\n", n, name, alphabet_count) 
  
}

输出:

2:GFG, 3

范例2:

// Golang program to illustrate the usage of 
// fmt.Sscan() function 
  
// Including the main package 
package main 
  
// Importing fmt 
import ( 
    "fmt"
) 
  
// Calling main 
func main() { 
  
    // Declaring some variables 
    var name string 
    var alphabet_count int
    var float_value float32 
    var boolean_value bool
  
    // Calling the Sscan() function which 
    // returns the number of elements 
    // successfully scanned and error if 
    // it persists 
    n, err:= fmt.Sscan("GeeksforGeeks 13 6.7 true",  
     &name, &alphabet_count, &float_value, &boolean_value) 
  
    // Below statements get 
    // executed if there is any error 
    if err != nil { 
        panic(err) 
    } 
  
    // Printing the number of  
    // elements and each elements also 
    fmt.Printf("%d:%s, %d, %g, %t", n, name,  
     alphabet_count, float_value, boolean_value) 
  
}

输出:

4:GeeksforGeeks, 13, 6.7, true



相关用法


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