【问题标题】:fmt.Scanf not working properly in Gofmt.Scanf 在 Go 中无法正常工作
【发布时间】:2014-10-24 04:30:35
【问题描述】:

我正在尝试一个应该测试 fmt.Scanf 的 sn-p,但它似乎没有按预期工作:

package main

import (
    "fmt"
    "time"
)

func main() {
    fmt.Println("What is your favorite color?")
    var favoriteColor string
    fmt.Scanf("%s", &favoriteColor)
    fmt.Println("Fave color is", favoriteColor)
    fmt.Println("What is your favorite food?")
    var myfood string
    fmt.Scanf("%s", &myfood)
    fmt.Printf("I like %s too!\n", myfood)
    fmt.Printf("Wait two seconds please...\n")
    time.Sleep(2000 * time.Millisecond)
    fmt.Printf("Your favorite color is %s, and the food you like best is %q\n", favoriteColor, myfood)
}

然而只取第一个答案,程序继续到最后然后返回:

What is your favorite color?
red
Fave color is red
What is your favorite food?
I like  too!
Wait two seconds please...
Your favorite color is red, and the food you like best is ""

为什么第二个 scanf 函数被忽略了?这对我来说毫无意义。

我在 Windows 7 上使用最新的 64 位软件包安装了 Go。

【问题讨论】:

    标签: go scanf


    【解决方案1】:

    %s 之后放置一个\n,以便它使用您键入的换行符。否则换行符进入下一次扫描。

    【讨论】:

    • 我可以看出换行符正在进入下一次扫描,感谢您向我展示这个。
    • 完全正确.. 来自 C++ 背景,我对此很熟悉
    • @AceixSmart 实际上fmt.Scanf 在处理换行符的方式上与 C scanf 的行为略有不同。有关详细信息,请参阅文档。
    猜你喜欢
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 1970-01-01
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多