Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Scanf in Go

Tags:

go

scanf

I am not sure how to use Scanf function. Let's say I want to input number 10 on scan. By doing that, shouldn't the output be 0xA?

Also, how do I use the function with two or more scan arguments (e.g. fmt.Scanf("%x", &e, &f, &g))?

package main

import (
    "fmt"
)

func main() {

    var e int

    fmt.Scanf("%#X", &e)
    fmt.Println(e)

}
like image 676
dodo254 Avatar asked Dec 06 '22 14:12

dodo254


1 Answers

You have to first take your input as an int and then print the hex value :

package main

import (
    "fmt"
    "os"
)

func main() {

    var e int

    fmt.Scanf("%d", &e)
    fmt.Fprintf(os.Stdout, "%#X\n", e)

}

Output is :

go run main.go 
10
0XA

For multiple inputs :

package main

import (
    "fmt"
    "os"
)

func main() {

    var e int
    var s string

    fmt.Scanf("%d %s", &e, &s)
    fmt.Fprintf(os.Stdout, "%#X \t%s\n", e, s)

}

Output is :

go run main.go
10 hello
0XA     hello

Update : fmt.Scanf() vs fmt.Scan()

Scan is able to loop :

package main

import (
    "fmt"
    "os"
)

func main() {

    var e int
    var f int
    var g int

    fmt.Scan(&e, &f, &g)
    fmt.Fprintf(os.Stdout, "%d - %d - %d", e, f, g)
}

Output is :

go run main.go
10
11
12
10 - 11 - 12

Scanf is able to """filter""" from a formated string :

package main

import (
    "fmt"
    "os"
)

func main() {

    var e int
    var f int

    fmt.Scanf("%d Scanf %d", &e, &f)
    fmt.Fprintf(os.Stdout, "%d - %d", e, f)
}

Output is :

go run main.go 
10 Scanf 11
10 - 11
like image 185
papey Avatar answered Dec 14 '22 10:12

papey