fmt

最后更新于:2022-04-02 02:43:47

[TOC] ## fmt ### Sscan /Sscanf 从字符串中解析给变量 Sscan ``` var a int var s string var b int fmt.Sscan("123 abc\n456", &a, &s, &b) fmt.Println(a) //123 fmt.Println(s) //abc fmt.Println(b) //456 ``` Sscanf ``` var name string var age int n, err := fmt.Sscanf("Kim is 22 years old", "%s is %d years old", &name, &age) if err != nil { panic(err) } fmt.Printf("%d: %s, %d\n", n, name, age) // Output: // 2: Kim, 22 ``` ### Scan/Scanf 向控制台输入,并赋给变量 Scan ``` var a string var b string fmt.Scan(&a, &b) //输入hello word 可用空格会回车分开 fmt.Println(a) //hello fmt.Println(b) //word ``` Scanf ``` var a string var b string fmt.Scanf("%s\n%s", &a, &b) //如果是\n 则回车输入第二参数 空格或者为空则空格输入第二字符 fmt.Println(a) //hello fmt.Println(b) //word ``` ### Errorf 格式化 error ``` //等效于 errors.New("this is a erro : "+"not found") fmt.Errorf("this is a erro :%s","not found") ``` ### Fprintf / Fprint / Fprintln 指定标准输出流 ``` fmt.Fprintf(os.Stdout, "%s is %d years old.\n", "name", 123) ``` ### Printf ``` a := 0666 b := "hello" fmt.Printf("%d %[1]o %[1]o %#[1]o %[2]s \n", a,b) // 438 666 666 0666 hello %[2]s : 可表示用第二个值打印字符串 ``` ### `\r` 清空后在输出 ``` for { for _, r := range `-\|/` { fmt.Printf("\r%c", r) time.Sleep(100*time.Millisecond) } } time.Sleep(123*time.Second) // 变换着输出 -\|/ 的循环 ```
';