7

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)

}
Rick-777
  • 9,714
  • 5
  • 34
  • 50
dodo254
  • 519
  • 2
  • 7
  • 16

1 Answers1

16

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
papey
  • 3,854
  • 1
  • 19
  • 18
  • 4
    What is the difference between `Scanf` and `Scan`? This may sound trivial, but I'm kinda confused. What if format in `Scanf` is `%d smth %s`? It seems like "`smth`" doesn't have any purpose. – dodo254 May 01 '17 at 09:11