Home »
Golang »
Golang Reference
Golang fmt.Scanf() Function with Examples
Golang | fmt.Scanf() Function: Here, we are going to learn about the Scanf() function of the fmt package with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 09, 2021
fmt.Scanf()
In Go language, the fmt package implements formatted I/O with functions analogous to C's printf() and scanf(). The Scanf() function is an inbuilt function of the fmt package which is used to scan text read from standard input, storing successive space-separated values into successive arguments as determined by the format.
It accepts two parameters (format string, a ...interface{}) and returns the number of total items successfully Scanfned and an error if occurred during the read operation.
Syntax:
func Scanf(format string, a ...interface{}) (n int, err error)
Parameter(s):
- format : String format with the format verbs.
- 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.Scanf() 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.Scanf() function
package main
import (
"fmt"
)
func main() {
var number int
// Input a number
fmt.Print("Input a number: ")
n, err := fmt.Scanf("%d", &number)
// Print the value, n and err
fmt.Println("number: ", number)
fmt.Println(n, " Item(s) scanned.")
fmt.Println("Error: ", err)
}
Output:
RUN 1:
Input a number: 108
number: 108
1 Item(s) scanned.
Error: <nil>
RUN 2:
Input a number: Hello
number: 0
0 Item(s) scanned.
Error: expected integer
Example 2:
// Golang program to demonstrate the
// example of fmt.Scanf() function
package main
import (
"fmt"
)
func main() {
var name string
var age int
// Input name from the user
fmt.Print("Enter name: ")
fmt.Scanf("%s", &name)
// Input name from the user
fmt.Print("Enter age: ")
fmt.Scanf("%d", &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.Scanf() 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.Scanf("%d", &num1)
fmt.Print("Enter second number: ")
fmt.Scanf("%d", &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 »