按 Enter 时指定的默认值
我希望在按 Enter 时分配一个默认值而不给出一个。
根据我的经验,Go Playground 不处理 fmt.Scan 输入,因此我在此处引用代码:
(如果可能,请告诉我如何操作!)
package main
import (
"fmt"
"time"
)
func main() {
t := 0
fmt.Print("seconds? ")
fmt.Scan(&t)
time.Sleep(time.Duration(t) * time.Second)
fmt.Println("in", t)
}
我已将 t
的值初始化为 0
,但是当我按 Enter 时没有给出value 程序会等待,直到我给出一些值。我对错误检查不感兴趣(如果可能的话)。我只希望代码接受一次 Enter 按键,如 0
Enter。
I want a default value to be assigned when pressing Enter without giving one.
From my experience Go Playground doesn't handle fmt.Scan inputs, so I quote the code here:
(If it's possible, tell me how please!)
package main
import (
"fmt"
"time"
)
func main() {
t := 0
fmt.Print("seconds? ")
fmt.Scan(&t)
time.Sleep(time.Duration(t) * time.Second)
fmt.Println("in", t)
}
I've initialized the value of t
to 0
but when I press Enter without giving a value the program waits until I give some value. I'm not interested in error checking (if that's possible). I just want the code to accept a single Enter press, as 0
Enter.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用
fmt.Scanln()
而不是fmt.Scan()
:引用自
fmt.Scanln()
:另一方面,
fmt.Scan()
不会在换行符处停止,而是:一般来说,我建议使用
bufio.Scanner
按行读取输入,并对这些行执行您想要的任何操作(检查其是否为空,或按照您想要的方式解析它)。bufio.NewScanner()
允许您使用(预定义的) string 作为源(与strings.NewReader()
——为了方便测试)或者如果你想读取用户输入,则传递os.Stdin
。Simply use
fmt.Scanln()
instead offmt.Scan()
:Quoting from
fmt.Scanln()
:On the other hand,
fmt.Scan()
does not stop at a newline, but:In general I suggest to use
bufio.Scanner
to read input by lines, and do whatever you want to with the lines (check if its empty, or parse it the way you want).bufio.NewScanner()
allows you to use a (predefined) string as the source (combined withstrings.NewReader()
–for easy testing) or passos.Stdin
if you want to read user input.您可以使用bufio.Reader
You can use
bufio.Reader