fmt.Fscanln() Function in Golang With Examples
Last Updated :
05 May, 2020
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Fscanln() function in Go language scans the specified text, read from r and then stores successive space-separated values into successive arguments. This function stops scanning at a newline and after the final item, there must be a newline or EOF. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions.
Syntax:
func Fscanln(r io.Reader, a ...interface{}) (n int, err error)
Parameters: This function accepts two parameters which are illustrated below:
- r io.Reader: This parameter contains the scanned specified texts.
- a …interface{}: These parameters are accepting each specified elements.
Returns: It returns the number of items successfully scanned.
Example 1:
package main
import (
"fmt"
"io"
"strings"
)
func main() {
s := `gfg 9`
r := strings.NewReader(s)
var a string
var b int
for {
n, err := fmt.Fscanln(r, &a, &b)
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
fmt.Printf( "%d: %s, %d" , n, a, b)
}
}
|
Output:
2: gfg, 9
Example 2:
package main
import (
"fmt"
"io"
"strings"
)
func main() {
s := `gfg 9 true 5.78`
r := strings.NewReader(s)
var a string
var b int
var c bool
var d float32
for {
n, err := fmt.Fscanln(r, &a, &b, &c, &d)
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
fmt.Printf( "%d: %s, %d, %t, %g" , n, a, b, c, d)
}
}
|
Output:
4: gfg, 9, true, 5.78
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...