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

如何使用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条回答 默认 最新

  • dongping4901 2019-09-05 12:42
    关注

    Get rid of the scanner (you already said you prefer ReadLine()) and change your nextInt() function to call nextLine() like this:

    func nextInt() int {
        i, e := strconv.Atoi(nextLine())
        if e != nil {
            panic(e)
        }
        return i
    }
    

    (BTW It's not a good idea to panic on bad user input but I assume this is just a test and you wouldn't do that for production code :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题