在Go語言中,fmt軟件包使用與C的printf()和scanf()函數相似的函數來實現格式化的I /O。 Go語言中的fmt.Fscan()函數掃描指定的文本,從r中讀取,然後將連續的以空格分隔的值存儲到連續的參數中。在這裏,換行符被視為空格。此外,該函數在fmt包下定義。在這裏,您需要導入“fmt”包才能使用這些函數。
用法:
func Fscan(r io.Reader, a ...interface{}) (n int, err error)
參數:此函數接受兩個參數,如下所示:
- r io.Reader:此參數包含掃描的指定文本。
- a …interface{}:此參數接收每種類型的指定文本。
返回值:它返回成功掃描的項目數。
範例1:
// Golang program to illustrate the usage of
// fmt.Fscan() function
// Including the main package
package main
// Importing fmt, io and strings
import (
"fmt"
"os"
"strings"
)
// Calling main
func main() {
// Declaring some type of variables
var (
i int
b bool
s string
)
// Calling the NewReader() function to
// specify some type of texts.
// variable "r" contains the scanned texts
r:= strings.NewReader("10 false GFG")
// Calling the Fscan() function to receive
// the scanned texts
n, err:= fmt.Fscan(r, &i, &b, &s)
// If the above function returns an error then
// below statement will be executed
if err != nil {
fmt.Fprintf(os.Stderr, "Fscanf:%v\n", err)
}
// Printing each type of scanned texts
fmt.Println(i, b, s)
// It returns the number of items
// successfully scanned
fmt.Println(n)
}
輸出:
10 false GFG 3
範例2:
// Golang program to illustrate the usage of
// fmt.Fscan() function
// Including the main package
package main
// Importing fmt, io and strings
import (
"fmt"
"os"
"strings"
)
// Calling main
func main() {
// Declaring some type of variables
var (
i int
b bool
s string
f float32
)
// Calling the NewReader() function to
// specify some type of texts.
// variable "r" contains the scanned texts
r:= strings.NewReader("46 true 3.4 GeeksforGeeks")
// Calling the Fscan() function to receive
// the scanned texts
n, err:= fmt.Fscan(r, &i, &b, &f, &s)
// If the above function returns an error then
// below statement will be executed
if err != nil {
fmt.Fprintf(os.Stderr, "Fscanf:%v\n", err)
}
// Printing each type of scanned texts
fmt.Println(i, b, f, s)
// It returns the number of items
// successfully scanned
fmt.Println(n)
}
輸出:
46 true 3.4 GeeksforGeeks 4
相關用法
- Golang math.Lgamma()用法及代碼示例
- Golang math.Float64bits()用法及代碼示例
- Golang atomic.AddInt64()用法及代碼示例
- Golang atomic.StoreInt64()用法及代碼示例
- Golang reflect.FieldByIndex()用法及代碼示例
- Golang string.Contains用法及代碼示例
- Golang bits.Sub()用法及代碼示例
- Golang io.PipeWriter.CloseWithError()用法及代碼示例
- Golang time.Round()用法及代碼示例
- Golang reflect.AppendSlice()用法及代碼示例
- Golang reflect.ChanOf()用法及代碼示例
- Golang flag.Bool()用法及代碼示例
- Golang time.Sleep()用法及代碼示例
- Golang time.Time.Year()用法及代碼示例
- Golang reflect.DeepEqual()用法及代碼示例
- Golang reflect.Indirect()用法及代碼示例
- Golang reflect.CanAddr()用法及代碼示例
- Golang reflect.CanInterface()用法及代碼示例
- Golang reflect.CanSet()用法及代碼示例
- Golang reflect.Cap()用法及代碼示例
注:本文由純淨天空篩選整理自Kanchan_Ray大神的英文原創作品 fmt.Fscan() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。