dougu4704 2016-10-14 05:36
浏览 104
已采纳

在golang中读取行

There are so many option to do this in Go. For example:

scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
    fmt.Println(scanner.Text())
}

or

reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('
')

Neither is working in my case. I am unable to find the reason why new line scan is not working.

Here's the question I'm working on: https://www.hackerrank.com/challenges/30-dictionaries-and-maps

And here's my code:

package main
import (
    "fmt"
    "bufio"
    "os"
    "strings"
)

func main() {
    var count int
    fmt.Scan(&count)

    m := make(map[string]string)
    for i := 0; i<count; i++{
        reader := bufio.NewReader(os.Stdin)
        text,err := reader.ReadString('
')
        if err != nil {
           fmt.Println(err)
        }
        value := strings.Fields(text)
        m[value[0]] = value[1]
    }
    var names []string
    for i := 0; i<count; i++{
        var name string
        fmt.Scan(&name)
        names = append(names,name)
    }

    for j:= 0; j<len(names);j++{
        if m[names[j]] != ""{
            fmt.Println(names[j] +" = "+ m[names[j]])
        }else{
            fmt.Println("Not found")
        }

    }

}

It is working in my editor, but when I use the question's input, it doesn't work.

  • 写回答

2条回答 默认 最新

  • doutuanxiao4619 2016-10-15 16:06
    关注

    As requested in the comments, here was my working example:

    package main
    
    import (
        "bufio"
        "fmt"
        "os"
    )
    
    func main() {
        phonebook := make(map[string]int)
    
        var count int
        fmt.Scan(&count)
        for i := 0; i < count; i++ {
            var name string
            var number int
            fmt.Scan(&name, &number)
            phonebook[name] = number
        }
    
        scanner := bufio.NewScanner(os.Stdin)
        for scanner.Scan() {
            name := scanner.Text()
            if number, ok := phonebook[name]; ok {
                fmt.Printf("%s=%d
    ", name, number)
            } else {
                fmt.Println("Not found")
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序 用oss下载 aliyun-oss-sdk-6.18.0.min client报错
  • ¥15 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥15 抖音看过的视频,缓存在哪个文件