down123321123
2016-03-25 05:19
浏览 332
已采纳

如何结束控制台中的`scanner.Scan`循环以获取golang?

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?

图片转代码服务由CSDN问答提供 功能建议

我希望程序接受两行(或更多行)的输入。 例如。

  1 2 3 4 
5 6 7 8 
   
 
 

根据官方文档,使用< / p>

 (用于扫描仪)。Scan(){
} 
   
 
 

将导致扫描无限行,直到到达 EOF或错误,是否还有其他函数会代替两行输入?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dregduc63699 2016-03-25 14:30
    已采纳

    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
    ", 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:
    
    $
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongliulu1122 2017-12-20 09:22

    Ask the user to press "CTRL + D", that signals the EOF from the terminal, your above code should work without any change.

    评论
    解决 无用
    打赏 举报
  • douliaodun9153 2017-12-31 00:18

    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
       }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题