I want to get string from stdio with func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)
but my code doent work correctly.
I'm leaning about golang. I want to know about how to get string from standard input with ReadLine()
I know, fmt.Scan
or Scanner
help me, but I want to use ReadLine()
package main
import (
"bufio"
"fmt"
"io"
"os"
"strconv"
)
var sc = bufio.NewScanner(os.Stdin)
var rd = bufio.NewReaderSize(os.Stdin, 1000000)
func nextInt() int {
sc.Scan()
i, e := strconv.Atoi(sc.Text())
if e != nil {
panic(e)
}
return i
}
func nextLine() string {
buf := make([]byte, 0, 1000000)
for {
line, isPrefix, err := rd.ReadLine()
if err == io.EOF {
break
} else if err != nil {
panic(err)
}
buf = append(buf, line...)
if !isPrefix {
break
}
}
return string(buf)
}
func main() {
var s string
var a int
s = nextLine()
a = nextInt()
fmt.Println(s)
fmt.Println(a)
}
- Result
$ ./a.out
test # input
334 # input
test
334
$ cat in.txt
test
334
$ ./a.out < in.txt
panic: strconv.Atoi: parsing "": invalid syntax
goroutine 1 [running]:
main.nextInt(0xc042056088)
I expect the two output should have been same, but when I use redirection, it didn't work and get different output.