當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。