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


Golang fmt.Sscanln()用法及代碼示例

在Go語言中,fmt軟件包使用與C的printf()和scanf()函數相似的函數來實現格式化的I /O。 Go語言中的fmt.Sscanln()函數掃描指定的字符串,並將連續的以空格分隔的值存儲到連續的參數中。此函數停止在換行符處掃描,並且在最後一個項目之後必須有換行符或EOF。此外,該函數在fmt包下定義。在這裏,您需要導入“fmt”包才能使用這些函數。

用法:

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

參數:此函數接受兩個參數,如下所示:

  • str string:此參數包含將要掃描的指定文本。
  • a …interface{}:此參數接收字符串的每個元素。

返回值:它返回成功掃描的項目數。

範例1:



// Golang program to illustrate the usage of 
// fmt.Sscanln() 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
  
    // Calling Sscanln() function 
    n, err:= fmt.Sscanln("GFG 3", &name, &alphabet_count) 
  
    // Checking if the function 
    // returns any error 
    if err != nil { 
        panic(err) 
    } 
  
    // Printing the number of elements  
    // present in the specified string 
    // and also the elements 
    fmt.Printf("n:%d, name:%s, alphabet_count:%d", 
                             n, name, alphabet_count) 
  
}

輸出:

n:2, name:GFG, alphabet_count:3

範例2:

// Golang program to illustrate the usage of 
// fmt.Sscanln() 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
  
    // Calling Sscanln() function 
    fmt.Sscanln("GFG \n 3", &name, &alphabet_count) 
  
    // Printing the elements of the string 
    fmt.Printf("name:%s, alphabet_count:%d", name, alphabet_count) 
  
}

輸出:

name:GFG, alphabet_count:0

在上麵的示例中,可以看到alphabet_count的分配值仍為3,但輸出仍為0,這是因為兩個元素“GFG”和“alphabet_count”之間存在換行(\ n),因此該函數停止在換行處掃描。




相關用法


注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 fmt.Sscanln() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。