英文:
How do I end `scanner.Scan` loop in console for golang?
问题
我有两行(或可能更多)输入,我希望程序能够接受。例如:
1 2 3 4
5 6 7 8
根据官方文档,使用以下代码可以无限读取输入行,直到遇到EOF或错误:
for scanner.Scan() {
}
是否有其他函数可以只读取两行输入呢?
英文:
I have two (or potentially more) lines of input that I would like the program to take. eg.
1 2 3 4
5 6 7 8
According to the official doc, using
for scanner.Scan() {
}
will cause infinite lines to be scan until it reach EOF or error, are there other functions that will take two lines of input instead?
答案1
得分: 17
传统上,使用空行(长度为零)来结束从标准输入(stdin)读取的用户输入是一种常见做法。例如,
package main
import (
"bufio"
"fmt"
"io"
"os"
"strings"
)
func main() {
snr := bufio.NewScanner(os.Stdin)
enter := "输入一行数据:"
for fmt.Println(enter); snr.Scan(); fmt.Println(enter) {
line := snr.Text()
if len(line) == 0 {
break
}
fields := strings.Fields(line)
fmt.Printf("字段: %q\n", fields)
}
if err := snr.Err(); err != nil {
if err != io.EOF {
fmt.Fprintln(os.Stderr, err)
}
}
}
输出:
$ go run data.go
输入一行数据:
1 2 3 4
字段: ["1" "2" "3" "4"]
输入一行数据:
5 6 7 8
字段: ["5" "6" "7" "8"]
输入一行数据:
$
英文:
It's traditional to end user input from stdin with an empty (zero length) line. For example,
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)
}
}
}
Output:
$ 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:
$
答案2
得分: 10
请用户按下"CTRL + D",这将从终端发送EOF信号,你上面的代码应该可以正常工作,无需任何更改。
英文:
Ask the user to press "CTRL + D", that signals the EOF from the terminal, your above code should work without any change.
答案3
得分: -1
一种方法是验证扫描器是否已经到达文件末尾。
var s scanner.Scanner
file, _ := os.Open("file.go") // 返回 io.Reader
s.Init(file) // 需要 io.Reader
var character rune
character = s.Scan()
for character != scanner.EOF {
// 在这里编写你的代码
}
英文:
One way to do this is to verify if the scanner has reached the end of the file.
var s scanner.Scanner
file, _ := os.Open("file.go") // return io.Reader
s.Init(file) // needs io.Reader
var character rune
character = s.Scan()
for character != scanner.EOF {
// here your code
}
答案4
得分: -2
使用Ctrl+Z来结束scanner.Scan()。
英文:
use ctl+z to end scanner.Scan()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论