fmt.Scanf在Go中无法正常工作 [英] fmt.Scanf not working properly in Go

查看:83
本文介绍了fmt.Scanf在Go中无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试fmt.Scanf的代码段,但似乎无法按预期工作:

I'm trying out a snippet that is supposed to test out fmt.Scanf, but it doesn't seem to work as expected:

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

但是,只有第一个答案会执行,程序会继续执行到最后,然后返回:

However only the first answer is taken, the program continues to the end and then returns:

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函数被忽略?对我来说这没有意义.

Why is the second scanf function being ignored? It makes no sense to me.

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

I installed Go using the most recent 64bit package on Windows 7.

推荐答案

%s 之后放置 \ n ,这样它将使用您键入的换行符.否则,换行符将进入下一次扫描.

Put a \n after the %s so it consumes the newline you type. Otherwise the newline goes into the next scan.

这篇关于fmt.Scanf在Go中无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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