go fmt.scanf获取输入的时候,如何获取到包含空格的句子?

我试图通过fmt.scanf输入一个句子存入变量,但是scanf函数将空格后面的单词识别成了下一次输入的内容。
请问如何避免这个问题呢?

代码如下所示:

package main

import (
    "fmt"
    "strings"
)

func main() {
    var quote string
    var name string

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

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

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

输出如下:

What is the quote? I am Groot
Who said it? Am says, "I"

已尝试过bufio包,但是我想找到只用fmt包的方法

阅读 14.1k
4 个回答
/*
Copyright 2017 by GoSpider author.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License
*/
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)
}

// Scanf
// fmt包真的就不能有空格,只能改造它的包! 呵呵。

/*

    What is the quote? 不要台固执 都是包
    Who said it? 不是你写 就是我写
    不是你写 就是我写 says, "不要台固执 都是包"

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

你可以用fmt.Scanln()输入一行内容

reader := bufio.NewReader(os.Stdin)

data, _, _ := reader.ReadLine()

fmt.Println(string(data))

试试这个

一楼和二楼说的都很好

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏