Função fmt.Sscanln() em Golang com exemplos
Na linguagem Go, o pacote fmt implementa E / S formatada com funções análogas às funções printf() e scanf() do C. A função fmt.Sscanln() na linguagem Go verifica a string especificada e armazena os valores separados por espaço sucessivos em argumentos sucessivos. Esta função interrompe a digitalização em uma nova linha e após o item final, deve haver uma nova linha ou EOF. Além disso, essa função é definida no pacote fmt. Aqui, você precisa importar o pacote “fmt” para usar essas funções.
Sintaxe:
func Sscanln(str string, a ...interface{}) (n int, err error)
Parâmetros: esta função aceita dois parâmetros que são ilustrados a seguir:
- str string: Este parâmetro contém o texto especificado que será verificado.
- a… interface {}: Este parâmetro recebe cada elemento da string.
Retorna: Retorna o número de itens verificados com sucesso.
Exemplo 1:
// 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)
}
Saída:
n: 2, name: GFG, alphabet_count: 3
Exemplo 2:
// 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)
}
Saída:
name: GFG, alphabet_count: 0
No exemplo acima, pode ser visto que o valor atribuído de alphabet_count foi 3, mas a saída é 0, isso é porque há uma nova linha (\ n) entre dois elementos “GFG” e “alphabet_count” e, portanto, esta função para digitalizando em uma nova linha.
As postagens do blog Acervo Lima te ajudaram? Nos ajude a manter o blog no ar!
Faça uma doação para manter o blog funcionando.
70% das doações são no valor de R$ 5,00...
Diógenes Lima da Silva