fmt.Scanf() Function in Golang With Examples
In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Scanf() function in Go language scans the input texts which is given in the standard input, reads from there and stores the successive space-separated values into successive arguments as determined by the format. 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 Scanf(format string, a ...interface{}) (n int, err error)
Parameters: This function accepts two parameters which are illustrated below:
- format string: This is the different formats which are used for each given elements.
- a …interface{}: These parameters receive each given elements.
Returns: It returns the number of items successfully scanned.
Example 1:
C
// Golang program to illustrate the usage of // fmt.Scanf() function // Including the main package package main // Importing fmt import ( "fmt" ) // Calling main func main() { // Declaring some variables var name string var alphabet_count int // Calling Scanf() function for // scanning and reading the input // texts given in standard input fmt.Scanf( "%s" , &name) fmt.Scanf( "%d" , &alphabet_count) // Printing the given texts fmt.Printf( "The word %s containing %d number of alphabets." , name, alphabet_count) } |
Input:
GFG 3
Output:
The word GFG containing 3 number of alphabets.
Example 2:
C
// Golang program to illustrate the usage of // fmt.Scanf() function // Including the main package package main // Importing fmt import ( "fmt" ) // Calling main func main() { // Declaring some variables var name string var alphabet_count int var float_value float32 var bool_value bool // Calling Scanf() function for // scanning and reading the input // texts given in standard input fmt.Scanf( "%s" , &name) fmt.Scanf( "%d" , &alphabet_count) fmt.Scanf( "%g" , &float_value) fmt.Scanf( "%t" , &bool_value) // Printing the given texts fmt.Printf( "%s %d %g %t" , name, alphabet_count, float_value, bool_value) } |
Input:
w3wiki 13 6.789 true
Output:
w3wiki 13 6.789 true
Contact Us