Golang fmt.Scanln() Function with Examples

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

fmt.Scanln()

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

It accepts one parameter (a ...interface{}) and returns the number of total items successfully scanned and an error if occurred during the read operation.

Syntax:

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

Parameter(s):

  • 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.Scanln() 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.Scanln() function

package main

import (
	"fmt"
)

func main() {
	var str string

	// Input a string
	fmt.Print("Input a string: ")
	n, err := fmt.Scanln(&str)

	// Print the value, n and err
	fmt.Println("str: ", str)
	fmt.Println(n, " Item(s) scanned.")
	fmt.Println("Error: ", err)
}

Output:

RUN 1:
Input a string: Alvin
str:  Alvin
1  Item(s) scanned.
Error:  <nil>

RUN 2:
Input a string: Dev Mohan
str:  Dev
1  Item(s) scanned.
Error:  expected newline

Example 2:

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

package main

import (
	"fmt"
)

func main() {
	var name string
	var age int

	// Input name from the user
	fmt.Print("Enter name: ")
	fmt.Scanln(&name)

	// Input name from the user
	fmt.Print("Enter age: ")
	fmt.Scanln(&age)

	// Print the entered values
	fmt.Println("Name: ", name)
	fmt.Println("Age : ", age)
}

Output:

Enter name: Alvin
Enter age: 21
Name:  Alvin
Age :  21

Example 3:

// Golang program to demonstrate the
// example of fmt.Scanln() function
// Input two numbers & find their sum

package main

import (
	"fmt"
)

func main() {
	var num1 int
	var num2 int
	var sum int

	// Input numbers
	fmt.Print("Enter first number: ")
	fmt.Scanln(&num1)

	fmt.Print("Enter second number: ")
	fmt.Scanln(&num2)

	// Calculate sum
	sum = num1 + num2

	// Printing the values & sum
	fmt.Printf("%d + %d = %d\n", num1, num2, sum)
}

Output:

Enter first number: 108
Enter second number: 101
108 + 101 = 209

Golang fmt Package »





Comments and Discussions!

Load comments ↻






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