dongxing8009 2017-04-30 16:56
浏览 157

了解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)

}
  • 写回答

1条回答 默认 最新

  • dongyan4424 2017-04-30 20:51
    关注

    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
    ", 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
    ", 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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog