doupaxia2478
2019-09-05 11:42
采纳率: 100%
浏览 184
已采纳

如何使用ReadLine()获取字符串输入?

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.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题