Read line in golang

两盒软妹~` 提交于 2019-12-06 14:55:26

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\n", name, number)
        } else {
            fmt.Println("Not found")
        }
    }
}

First of all, you initiate your reader each time in a loop.
Second, if you go with Reader, stick with it. You initialize input reader, then try to go back to fmt.Scan, but Reader already got your input.
Third, remember that you need to .Trim() your input

    package main

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

    func main() {
        var count int
        fmt.Scan(&count)
        reader := bufio.NewReader(os.Stdin)
        m := make(map[string]string)
        for i := 0; i<count; i++{

            text,err := reader.ReadString('\n')
            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
            name, _ = reader.ReadString('\n')
            names = append(names,strings.Trim(name, " \n"))
        }

        for _, name := range names {

            phone, found := m[name]
            if found {
                fmt.Println(name +"="+ phone)
            }else{
                fmt.Println("Not found")
            }

        }

    }
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!