dspld86684 2019-01-10 06:57
浏览 2523

Golang中的bufio.NewReader(os.Stdin)和fmt.Scanln()有什么区别[关闭]

package main

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

func main() {
    in := bufio.NewReader(os.Stdin)
    fmt.Println("Please input S: ")
    S, _ := in.ReadString('
')
    fmt.Println("Please input J: ")
    J, _ := in.ReadString('
')
    sum := numJewelsInStones(J,S)
    fmt.Println(sum)
}

func numJewelsInStones(J string, S string) int {
    var sum  int
    for _, s := range S {
        for _, j := range J{
            if s ==j {
                sum ++
            }
        }

    }
    return sum
}

When I input "hello" and "h" at the terminal. This program will print 2, but except is 1.
And If i use fmt.Scanln(), the result will be 1.
What caused this result?

  • 写回答

1条回答 默认 最新

  • dtewnsdf47253 2019-01-10 08:11
    关注

    They are completely different and mostly unrelated.

    bufio.NewReader() "wraps an io.Reader or io.Writer object, creating another object (Reader or Writer) that also implements the interface but provides buffering and some help for textual I/O". source.

    In other words, all it does, is add a buffering layer to (in your example), os.Stdin. It does no parsing or interpretation of the stream at all.

    In contrast, fmt.Scanln() reads data from a stream (which may or may not be buffered--i.e. returned by the bufio package), splitting the input by whitespace, to store it in a slice.

    By reading the documentation (to which I have linked above), you can get specific details of each. But the direct answer to your question "What's the difference?" is simply "Absolutely everything. They have practically nothing in common, although they can be used together."

    评论

报告相同问题?

悬赏问题

  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致