首页 > 请大神帮我看下问题出在哪?

请大神帮我看下问题出在哪?

有下面两个文件。
我在temp数组后面追加读取出来的数据,为什么在for循环里面能正确读取temp的信息,但是执行后for循环后,temp的信息就打印不出来了?求大神帮忙看下,是什么问题?

read_demo.go

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
)

// var temp []string

func main() {
    inputFile, inputError := os.Open("products2.txt")
    if inputError != nil {
        fmt.Printf("An error occurred on opening the inputfile\n" +
            "Does the file exist?\n" +
            "Have you got acces to it?\n")
        return // exit the function on error
    }
    defer inputFile.Close()

    inputReader := bufio.NewReader(inputFile)
    var temp []string
    for {
        inputString, readerError := inputReader.ReadString('\n')
        if readerError == io.EOF {
            return
        }
        temp = append(temp, inputString)
        fmt.Println(temp)
        // fmt.Printf("The input was: %s", inputString)
    }

    fmt.Println(temp) // 打印内容为空
}

products2.txt

"The ABC of Go";25.5;1500
"Functional Programming with Go";56;280
"Go for It";45.9;356
"The Go Way";55;500


你最后打印的那条代码没有执行机会的
看一下你for循环里面的逻辑,你每次读一行打印,到最后读完之后,你判断为io.EOF之后程序怎么走,直接就return了

【热门文章】
【热门文章】