使用空(零长度)行从 stdin 结束用户输入是传统的做法。例如,
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
func main() {
snr := bufio.NewScanner(os.Stdin)
enter := "Enter a line of data:"
for fmt.Println(enter); snr.Scan(); fmt.Println(enter) {
line := snr.Text()
if len(line) == 0 {
break
}
fields := strings.Fields(line)
fmt.Printf("Fields: %q\n", fields)
}
if err := snr.Err(); err != nil {
if err != io.EOF {
fmt.Fprintln(os.Stderr, err)
}
}
}
输出:
$ go run data.go
Enter a line of data:
1 2 3 4
Fields: ["1" "2" "3" "4"]
Enter a line of data:
5 6 7 8
Fields: ["5" "6" "7" "8"]
Enter a line of data:
$