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


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

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

用法:

func Scanln(a ...interface{}) (n int, err error)

在這裏,“……接口{}”接收每個給定的文本。

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

範例1:



// Golang program to illustrate the usage of 
// fmt.Scanln() 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 Scanln() function for 
    // scanning and reading the input 
    // texts given in standard input 
    fmt.Scanln(&name) 
    fmt.Scanln(&alphabet_count) 
  
    // Printing the given texts 
    fmt.Printf("%s %d",  
               name, alphabet_count) 
  
}

輸入:

GFG 3

輸出:

GFG 0

範例2:

// Golang program to illustrate the usage of 
// fmt.Scanln() 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 Scanln() function for 
    // scanning and reading the input 
    // texts given in standard input 
    fmt.Scanln(&name) 
    fmt.Scanln(&alphabet_count) 
  
    // Printing the given texts 
    fmt.Printf("%s %d",  
               name, alphabet_count) 
  
}

輸入:

GeeksforGeeks \n 13

輸出:

GeeksforGeeks 0

在上麵的示例中,可以看到標準輸入取值為“ GeeksforGeeks \ n 13”,但它返回的輸出為“ GeeksforGeeks 0”,這是因為此函數在新行(\ n)處停止了掃描。




相關用法


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