fmt.Sscanln() 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.Sscanln() function in Go language scans the specified string and stores the successive space-separated values into successive arguments. This function stops scanning at a newline and after the final item, there must be a newline or EOF. 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 Sscanln(str string, a ...interface{}) (n int, err error)

Parameters: This function accepts two parameters which are illustrated below:

  • str string: This parameter contains the specified text which is going to be scanned.
  • a …interface{}: This parameter receives each elements of the string.

Returns: It returns the number of items successfully scanned.

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate the usage of
// fmt.Sscanln() 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 Sscanln() function
    n, err := fmt.Sscanln("GFG 3", &name, &alphabet_count)
  
    // Checking if the function
    // returns any error
    if err != nil {
        panic(err)
    }
  
    // Printing the number of elements 
    // present in the specified string
    // and also the elements
    fmt.Printf("n: %d, name: %s, alphabet_count: %d",
                             n, name, alphabet_count)
  
}

chevron_right


Output:

n: 2, name: GFG, alphabet_count: 3

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Golang program to illustrate the usage of
// fmt.Sscanln() 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 Sscanln() function
    fmt.Sscanln("GFG \n 3", &name, &alphabet_count)
  
    // Printing the elements of the string
    fmt.Printf("name: %s, alphabet_count: %d", name, alphabet_count)
  
}

chevron_right


Output:

name: GFG, alphabet_count: 0

In the above example, it can be seen that the assigned value of alphabet_count was 3 still the output is 0 this is because of there is new line (\n) in between two elements “GFG” and “alphabet_count” and hence this function stop scanning at a newline.




My Personal Notes arrow_drop_up

Recommended Posts:

    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.