英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论