Understanding Scanf in Go

huangapple go评论112阅读模式
英文:

Understanding Scanf in Go

问题

我不确定如何使用Scanf函数。假设我想在扫描时输入数字10。那么输出应该是0xA吗?

另外,我如何在函数中使用两个或更多的扫描参数(例如fmt.Scanf("%x", &e, &f, &g))?

package main

import (
	"fmt"
)

func main() {
	var e int

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

请注意,我只会翻译代码部分,不会回答关于代码的问题。

英文:

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

得分: 16

你需要首先将输入作为整数进行处理,然后打印其十六进制值:

package main

import (
	"fmt"
	"os"
)

func main() {

	var e int

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

}

输出结果为:

go run main.go 
10
0XA

对于多个输入:

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)

}

输出结果为:

go run main.go
10 hello
0XA 	hello

更新:fmt.Scanf() vs fmt.Scan()

Scan可以循环读取输入:

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)
}

输出结果为:

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

Scanf可以从格式化字符串中进行过滤:

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)
}

输出结果为:

go run main.go 
10 Scanf 11
10 - 11
英文:

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

huangapple
  • 本文由 发表于 2017年5月1日 00:56:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/43708943.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定