在Go語言中,fmt軟件包使用與C的printf()和scanf()函數相似的函數來實現格式化的I /O。 Go語言中的fmt.Fscanln()函數掃描指定的文本,從r中讀取,然後將連續的以空格分隔的值存儲到連續的參數中。此函數停止在換行符處掃描,並且在最後一個項目之後必須有換行符或EOF。此外,該函數在fmt包下定義。在這裏,您需要導入“fmt”包才能使用這些函數。
用法:
func Fscanln(r io.Reader, a ...interface{}) (n int, err error)
參數:此函數接受兩個參數,如下所示:
- r io.Reader:此參數包含掃描的指定文本。
- a …interface{}:這些參數接受每個指定的元素。
返回值:它返回成功掃描的項目數。
範例1:
// Golang program to illustrate the usage of
// fmt.Fscanln() function
// Including the main package
package main
// Importing fmt, io and strings
import (
"fmt"
"io"
"strings"
)
// Calling main
func main() {
// Declaring list of strings,
// integers and float value
s:= `gfg 9`
// Calling NewReader() function for
// reading each elements of the list
// and then it place it into "r"
r:= strings.NewReader(s)
// Declaring different types of variables
var a string
var b int
for {
// Calling Fscanln() function
n, err:= fmt.Fscanln(r, &a, &b)
// Checking returned error is
// end of the line (EOF) or not
if err == io.EOF {
break
}
// Checking if there is any error
if err != nil {
panic(err)
}
// Printing the number of items successfully
// scanned and each elements too
fmt.Printf("%d:%s, %d", n, a, b)
}
}
輸出:
2:gfg, 9
範例2:
// Golang program to illustrate the usage of
// fmt.Fscanln() function
// Including the main package
package main
// Importing fmt, io and strings
import (
"fmt"
"io"
"strings"
)
// Calling main
func main() {
// Declaring list of strings,
// integers and float value
s:= `gfg 9 true 5.78`
// Calling NewReader() function for
// reading each elements of the list
// and then it place it into "r"
r:= strings.NewReader(s)
// Declaring different types of variables
var a string
var b int
var c bool
var d float32
for {
// Calling Fscanln() function
n, err:= fmt.Fscanln(r, &a, &b, &c, &d)
// Checking returned error is
// end of the line (EOF) or not
if err == io.EOF {
break
}
// Checking if there is any error
if err != nil {
panic(err)
}
// Printing the number of items successfully
// scanned and each elements too
fmt.Printf("%d:%s, %d, %t, %g", n, a, b, c, d)
}
}
輸出:
4:gfg, 9, true, 5.78
相關用法
- 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.Fscanln() Function in Golang With Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。