fmt.Scan在Go中无法正常工作

时间:2014-10-23 20:23:16

标签: go scanf

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

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。

1 个答案:

答案 0 :(得分:7)

\n之后放置%s,以便消耗您输入的换行符。否则换行进入下一次扫描。