按下回车键时分配的默认值

huangapple go评论84阅读模式
英文:

Default value assigned when pressing Enter

问题

当按下<kbd>Enter</kbd>键而没有提供值时,我希望分配一个默认值。

根据我的经验,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,但是当我按下<kbd>Enter</kbd>键而没有提供值时,程序会等待我提供某个值。我不关心错误检查(如果可能的话)。我只想让代码接受单个<kbd>Enter</kbd>键按下,作为 0 <kbd>Enter</kbd>。

英文:

I want a default value to be assigned when pressing <kbd>Enter</kbd> 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 (
	&quot;fmt&quot;
	&quot;time&quot;
)

func main() {
	t := 0
	fmt.Print(&quot;seconds? &quot;)
	fmt.Scan(&amp;t)
	time.Sleep(time.Duration(t) * time.Second)
	fmt.Println(&quot;in&quot;, t)
}

I've initialized the value of t to 0 but when I press <kbd>Enter</kbd> 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 <kbd>Enter</kbd> press, as 0 <kbd>Enter</kbd>.

答案1

得分: 3

只需使用fmt.Scanln()而不是fmt.Scan()

fmt.Scanln(&t)

引用自fmt.Scanln()的说明:

Scanln类似于Scan,但在换行符处停止扫描,并且在最后一项之后必须有一个换行符或EOF。

另一方面,fmt.Scan()不会在换行符处停止,而是:

Scan从标准输入中扫描文本,将连续的以空格分隔的值存储到连续的参数中。换行符被视为空格

一般建议使用bufio.Scanner按行读取输入,并根据需要对行进行处理(检查是否为空,或按照所需方式解析)。如果要读取用户输入,可以使用bufio.NewScanner()并将os.Stdin作为源(与strings.NewReader()结合使用,方便进行测试)。

英文:

Simply use fmt.Scanln() instead of fmt.Scan():

fmt.Scanln(&amp;t)

Quoting from fmt.Scanln():

> Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF.

On the other hand, fmt.Scan() does not stop at a newline, but:

> Scan scans text read from standard input, storing successive space-separated values into successive arguments. Newlines count as space.

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 with strings.NewReader()–for easy testing) or pass os.Stdin if you want to read user input.

答案2

得分: 1

你可以使用bufio.Reader

package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
	"time"
)

func main() {
	var t int

	reader := bufio.NewReader(os.Stdin)
	fmt.Print("秒数?")
	for {
		tStr, err := reader.ReadString('\n')
		tStr = strings.TrimSpace(tStr)

		t, err = strconv.Atoi(tStr)
		if err != nil {
			fmt.Println("无效的输入,请输入一个数字")
			continue
		}
		break
	}

	time.Sleep(time.Duration(t) * time.Second)
	fmt.Println("经过", t, "秒")
}
英文:

You can use bufio.Reader

package main

import (
	&quot;bufio&quot;
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;strconv&quot;
	&quot;strings&quot;
	&quot;time&quot;
)

func main() {
	var t int

	reader := bufio.NewReader(os.Stdin)
	fmt.Print(&quot;seconds? &quot;)
	for {
		tStr, err := reader.ReadString(&#39;\n&#39;)
		tStr = strings.TrimSpace(tStr)

		t, err = strconv.Atoi(tStr)
		if err != nil {
			fmt.Println(&quot;invalid input, please write a number&quot;)
			continue
		}
		break
	}

	time.Sleep(time.Duration(t) * time.Second)
	fmt.Println(&quot;in&quot;, t)
}

huangapple
  • 本文由 发表于 2022年3月21日 21:45:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/71558665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定