go fmt.scanf获取输入的时候,获取到包含空格的字符串

方法一

scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
s1 := strings.ToLower(scanner.Text())

全部代码展示

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	s1 := strings.ToLower(scanner.Text())
	scanner.Scan()
	s2 := strings.ToLower(scanner.Text())
	count := 0
	for _, v := range s1 {
		if v == int32(s2[0]) {
			count++
		}
	}
	fmt.Println(count)
}

 

方法二

fmt包真的就不能有空格,只能改造它的包

func Scanf(a *string) {
    reader := bufio.NewReader(os.Stdin)
    data, _, _ := reader.ReadLine()
    *a = string(data)
}

全部代码展示

package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {
    var quote string
    var name string

    fmt.Print("What is the quote? ")
    Scanf(&quote)

    fmt.Print("Who said it? ")
    Scanf(&name)

    fmt.Printf("%s says, \"%s\"", strings.Title(name), quote)
}

func Scanf(a *string) {
    reader := bufio.NewReader(os.Stdin)
    data, _, _ := reader.ReadLine()
    *a = string(data)
}


版权声明:本文为zsllll9996原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。