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

查看:637
本文介绍了golang - 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包的方法

解决方案

/*
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)
}

这篇关于golang - go fmt.scanf获取输入的时候,如何获取到包含空格的句子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆