天天看點

golang_fmt包中Scanf和Sscanf的使用

func Scanf

Scanf從标準輸入掃描文本,根據format 參數指定的格式将成功讀取的空白分隔的值儲存進成功傳遞給本函數的參數。傳回成功掃描的條目個數和遇到的任何錯誤。

demo

package main

import "fmt"

func main() {
	var name string
	fmt.Printf("請輸入内容:")
	fmt.Scan(&name)
	fmt.Println("name:", name)

	fmt.Printf("請輸入内容2:")
	fmt.Scanf("%s", &name)
	fmt.Println("name:", name)
}
           

output:

請輸入内容:2345
name: 2345
請輸入内容2:1234
name: 1234
           

func Sscanf

Sscanf從字元串str掃描文本,根據format 參數指定的格式将成功讀取的空白分隔的值儲存進成功傳遞給本函數的參數。傳回成功掃描的條目個數和遇到的任何錯誤。

demo

package main

import "fmt"

func main() {
	s, t := "test123", ""
	fmt.Sscan(s, &t)
	fmt.Println("s:", s)
	fmt.Println("t:", t)	// t: test123 将s的内容傳給t

	fmt.Sscanln(s, &t)
	fmt.Println("s:", s)
	fmt.Println("t:", t)	// t: test123 将s的内容傳給t

	_, err := fmt.Sscanf(s, "test%s", &t)
	fmt.Println("err:", err)
	fmt.Println("s:", s)	// s: test123
	fmt.Println("t:", t)	// t: 123 将t從s中去掉“test”後提取出來
}