Golang fmt.Fscanln() Function with Examples

Golang | fmt.Fscanln() Function: Here, we are going to learn about the Fscanln() function of the fmt package with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 08, 2021

fmt.Fscanln()

In Go language, the fmt package implements formatted I/O with functions analogous to C's printf() and scanf(). The Fscanln() function is an inbuilt function of the fmt package. It is similar to Fscan() function, but it stops scanning at a newline and after the final item there must be a newline or EOF.

It accepts two parameters (r io.Reader, a ...interface{}) and returns the number of total items successfully scanned and an error if occurred during the read operation.

Syntax:

func Fscanln(r io.Reader, a ...interface{}) (n int, err error)

Parameter(s):

  • r : The standard Input/Output.
  • a : A custom type that is used to specify a set of one or more method signatures, here we can provide a set of the variables, constants, functions, etc.

Return Value:

The return type of the fmt.Fscanln() function is (n int, err error), it returns the number of total items successfully scanned and an error if occurred during the read operation.

Example 1:

// Golang program to demonstrate the
// example of fmt.Fscanln() function

package main

import (
	"fmt"
	"strings"
)

func main() {
	var name string
	var age int

	// Function Fscanln() returns,
	// n: Number of items successfully scanned
	// err: Error if any
	n, err := fmt.Fscanln(strings.NewReader("Alexander 47\n"),
		&name, &age)

	// Printing variables, items scanned, err
	fmt.Println("Name :", name)
	fmt.Println("Age :", age)

	fmt.Println(n, "Items successfully scanned")
	fmt.Println("Error", err)
}

Output:

Name : Alexander
Age : 47
2 Items successfully scanned
Error <nil>

Example 2:

// Golang program to demonstrate the
// example of fmt.Fscanln() function

package main

import (
	"fmt"
	"strings"
)

func main() {
	var (
		name string
		roll int
		age  int
		perc float32
	)

	// Function Fscan() returns,
	// n: Number of items successfully scanned
	// err: Error if any
	n, err := fmt.Fscanln(strings.NewReader("Alvin 101 47 87.50"),
		&name, &roll, &age, &perc)

	// Printing variables, items scanned, err
	fmt.Println("Name :", name)
	fmt.Println("Roll :", roll)
	fmt.Println("Age :", age)
	fmt.Println("Percentage :", perc)

	fmt.Println(n, "Items successfully scanned")
	fmt.Println("Error", err)
}

Output:

Name : Alvin
Roll : 101
Age : 47
Percentage : 87.5
4 Items successfully scanned
Error <nil>

Golang fmt Package »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.