2017-08-28 170 views
2

輸入我有這樣的Go代碼:閱讀從標準輸入中golang

func readTwoLines() { 
    reader := bufio.NewReader(os.Stdin) 
    line, _ := reader.ReadString('\n') 
    fmt.Println(line) 
    line, _ = reader.ReadString('\n') 
    fmt.Println(line) 
} 

對於輸入:

hello 
bye 

輸出爲:

hello 
bye 

一切OK。但現在,如果我創建每行一個讀者:

func readTwoLines() { 
    line, _ := bufio.NewReader(os.Stdin).ReadString('\n') 
    fmt.Println(line) 
    line, err := bufio.NewReader(os.Stdin).ReadString('\n') 
    if err != nil { 
    fmt.Println(err) 
    }  
    fmt.Println(line) 
} 

有一個EOF錯誤,在第二行讀數。

爲什麼會發生?

回答

3

對於簡單的用途,Scanner可能會更方便。
你不應該使用兩個讀卡器,先讀緩衝區4096個字節的輸入的:

// 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)之前讀取數據。

它是由設計,看文檔:

// 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 

我希望這有助於。

+0

這是完美的!非常感謝你 –

+0

不客氣。 –