dsvcqvp139098 2017-04-11 15:28
浏览 81
已采纳

Golang从stdin行读取多个字段

$ echo "A 1 2 3 4" | go run test.go 
entire:  A
next field:  A

I need to read several lines from standard input that are like "A 1 2 3 4" (code does one line for now) and something goes wrong. Scanln should read the entire line and Fields should split it by newlines? Why does Scanln read only one word?

package main

import (
    "fmt"
    "strings"
)

func main() {
    var line string
    fmt.Scanln(&line)
    fmt.Println("entire: ",line)
    for _,x := range strings.Fields(line) {
        fmt.Println("next field: ",x)
    }
}

$ echo "A 1 2 3 4" | go run test.go 
entire:  A
next field:  A
  • 写回答

2条回答 默认 最新

  • duanbi1983 2017-04-11 17:51
    关注

    Have you tried:

    package main
    
    import (
        "fmt"
        "os"
        "bufio"
        "strings"
    )
    
    func main() {
        var line string
        scanner := bufio.NewScanner(os.Stdin)
        for scanner.Scan() {
            line = scanner.Text()
            fmt.Println("Got line:", line)
            for _, x := range strings.Fields(line) {
                fmt.Println("next field: ",x)
            }
        }
    }
    

    Then:

    $ printf "aa bb 
     cc dd " | go run 1.go  
    Got line: aa bb
    next field:  aa
    next field:  bb
    Got line:  cc dd
    next field:  cc
    next field:  dd
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 有人懂怎么做大模型的客服系统吗?卡住了卡住了
  • ¥20 firefly-rk3399上启动卡住了
  • ¥15 如何删除这个虚拟音频
  • ¥50 hyper默认的default switch
  • ¥15 网站打不开,提示502 Bad Gateway
  • ¥20 基于MATLAB的绝热压缩空气储能系统代码咨询
  • ¥15 R语言建立随机森林模型出现的问题
  • ¥15 中级微观经济学,生产可能性边界问题
  • ¥15 TCP传输时不同网卡传输用时差异过大
  • ¥15 请各位看看我写的属于什么算法,或者有更正确的写法?