'What's the difference between bufio.NewReader(os.Stdin) and fmt.Scanln() in Golang [closed]
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
in := bufio.NewReader(os.Stdin)
fmt.Println("Please input S: ")
S, _ := in.ReadString('\n')
fmt.Println("Please input J: ")
J, _ := in.ReadString('\n')
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 expected is 1.
And If i use fmt.Scanln(), the result will be 1.
What caused this result?
Solution 1:[1]
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."
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Flimzy |