was*_*mup 6
Scanner
// NewReader returns a new Reader whose buffer has the default size.
func NewReader(rd io.Reader) *Reader {
return NewReaderSize(rd, defaultBufSize)
}
defaultBufSize = 4096
甚至你的输入包含4000个字节,仍然第二次读取没有任何东西可读.但如果输入的输入超过4096字节,它将起作用.
如果ReadString在找到分隔符之前遇到错误,它将返回错误之前读取的数据和错误本身(通常是io.EOF).
它是按设计,见doc:
// ReadString reads until the first occurrence of delim in the input,
// returning a string containing the data up to and including the delimiter.
// If ReadString encounters an error before finding a delimiter,
// it returns the data read before the error and the error itself (often io.EOF).
// ReadString returns err != nil if and only if the returned data does not end in
// delim.
// For simple uses, a Scanner may be more convenient.
func (b *Reader) ReadString(delim byte) (string, error) {
bytes, err := b.ReadBytes(delim)
return string(bytes), err
}
试试这个:
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
fmt.Println(scanner.Text()) // Println will add back the final '\n'
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading standard input:", err)
}
}
跑:
go run m.go < in.txt
输出:
hello
bye
in.txt
hello
bye
我希望这有帮助.