猿问

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

我想从 stdio 获取字符串,func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)但我的代码无法正常工作。


我倾向于 golang。我想知道如何从标准输入获取字符串ReadLine()


我知道,fmt.Scan或者Scanner帮助我,但我想用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)

}


结果

$ ./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)


我预计两个输出应该是相同的,但是当我使用重定向时,它不起作用并得到不同的输出。


海绵宝宝撒
浏览 130回答 2
2回答

MMTTMM

摆脱扫描仪(您已经说过您更喜欢 ReadLine())并更改 nextInt() 函数以调用 nextLine(),如下所示:func nextInt() int {&nbsp; &nbsp; i, e := strconv.Atoi(nextLine())&nbsp; &nbsp; if e != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(e)&nbsp; &nbsp; }&nbsp; &nbsp; return i}(顺便说一句,对错误的用户输入感到恐慌并不是一个好主意,但我认为这只是一个测试,您不会对生产代码这样做:)

catspeake

你可以尝试不使用扫描仪,也许像这样 Readline 会为你获取数字,只需转换它package mainimport (&nbsp; &nbsp; "bufio"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "io"&nbsp; &nbsp; "os"&nbsp; &nbsp; "strconv")var rd = bufio.NewReaderSize(os.Stdin, 1000000)func nextLine() string {&nbsp; &nbsp; buf := make([]byte, 0, 1000000)&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; line, isPrefix, err := rd.ReadLine()&nbsp; &nbsp; &nbsp; &nbsp; if err == io.EOF {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; } else if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; buf = append(buf, line...)&nbsp; &nbsp; &nbsp; &nbsp; if !isPrefix {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return string(buf)}func main() {&nbsp; &nbsp; var s string&nbsp; &nbsp; var a int&nbsp; &nbsp; s = nextLine()&nbsp; &nbsp; fmt.Println(s)&nbsp; &nbsp; s = nextLine()&nbsp; &nbsp; a, e := strconv.Atoi(s)&nbsp; &nbsp; if e != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(e)&nbsp; &nbsp; }&nbsp; &nbsp; fmt.Println(a)}
随时随地看视频慕课网APP

相关分类

Go
我要回答