按 Enter 时分配的默认值
Default value assigned when pressing 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 时没有给出值,程序会等到我给出一些值.我对错误检查不感兴趣(如果可能的话)。我只想让代码接受一次 Enter 按下,因为 0
Enter.
只需使用fmt.Scanln()
instead of fmt.Scan()
:
fmt.Scanln(&t)
引用自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.
另一方面,fmt.Scan()
不会停在换行符处,而是:
Scan scans text read from standard input, storing successive space-separated values into successive arguments. Newlines count as space.
一般来说,我建议使用 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()
——为了便于测试)或者如果你想读取用户输入,则通过 os.Stdin
。
您可以使用bufio.Reader
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"time"
)
func main() {
var t int
reader := bufio.NewReader(os.Stdin)
fmt.Print("seconds? ")
for {
tStr, err := reader.ReadString('\n')
tStr = strings.TrimSpace(tStr)
t, err = strconv.Atoi(tStr)
if err != nil {
fmt.Println("invalid input, please write a number")
continue
}
break
}
time.Sleep(time.Duration(t) * time.Second)
fmt.Println("in", t)
}
我想在按 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 时没有给出值,程序会等到我给出一些值.我对错误检查不感兴趣(如果可能的话)。我只想让代码接受一次 Enter 按下,因为 0
Enter.
只需使用fmt.Scanln()
instead of fmt.Scan()
:
fmt.Scanln(&t)
引用自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.
另一方面,fmt.Scan()
不会停在换行符处,而是:
Scan scans text read from standard input, storing successive space-separated values into successive arguments. Newlines count as space.
一般来说,我建议使用 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()
——为了便于测试)或者如果你想读取用户输入,则通过 os.Stdin
。
您可以使用bufio.Reader
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
"time"
)
func main() {
var t int
reader := bufio.NewReader(os.Stdin)
fmt.Print("seconds? ")
for {
tStr, err := reader.ReadString('\n')
tStr = strings.TrimSpace(tStr)
t, err = strconv.Atoi(tStr)
if err != nil {
fmt.Println("invalid input, please write a number")
continue
}
break
}
time.Sleep(time.Duration(t) * time.Second)
fmt.Println("in", t)
}