Home »
Golang »
Golang Reference
Golang fmt.Sscanf() Function with Examples
Golang | fmt.Sscanf() Function: Here, we are going to learn about the Sscanf() function of the fmt package with its usages, syntax, and examples.
Submitted by IncludeHelp, on October 10, 2021
fmt.Sscanf()
In Go language, the fmt package implements formatted I/O with functions analogous to C's printf() and scanf(). The Sscanf() function is an inbuilt function of the fmt package which is used to scan the argument string, storing successive space-separated values into successive arguments as determined by the format.
It accepts three parameters (str string, format string, a ...interface{}) and returns the number of total items successfully parsed and an error if occurred during paring.
Syntax:
func Sscanf(str string, format string, a ...interface{}) (n int, err error)
Parameter(s):
- str : It contains the argument string to be extracted.
- 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.Sscanf() function is a string, it returns the number of total items successfully parsed and an error if occurred during paring.
Example 1:
// Golang program to demonstrate the
// example of fmt.Sscanf() function
package main
import (
"fmt"
)
func main() {
var x int
var y int
// Scans the values (space-separated)
// and assigns to the variables
fmt.Sscanf("10 20", "%d %d", &x, &y)
// Prints the values
fmt.Println("x:", x)
fmt.Println("y:", y)
// Scans the values (newline-separated)
// and assigns to the variables
fmt.Sscanf("30\n40", "%d\n%d", &x, &y)
// Prints the values
fmt.Println("x:", x)
fmt.Println("y:", y)
// Scans the values (Tab-separated)
// and assigns to the variables
fmt.Sscanf("50\t60", "%d\t%d", &x, &y)
// Prints the values
fmt.Println("x:", x)
fmt.Println("y:", y)
}
Output:
x: 10
y: 20
x: 30
y: 40
x: 50
y: 60
Example 2:
// Golang program to demonstrate the
// example of fmt.Sscanf() function
package main
import (
"fmt"
)
func main() {
// Assign the value to a string variable
data := "Alex 21 98.50"
// Declare the variables to store the values
var name string
var age int
var perc float32
// Scans the values and assigns
// to the variables
fmt.Sscanf(data, "%s %d %f", &name, &age, &perc)
// Prints the values
fmt.Println("Name:", name)
fmt.Println("Age:", age)
fmt.Println("Percentage:", perc)
}
Output:
Name: Alex
Age: 21
Percentage: 98.5
Golang fmt Package »