【问题标题】:Golang Read text file and take a slice from one of the read in valuesGolang 读取文本文件并从其中一个读入值中获取切片
【发布时间】:2016-02-14 16:17:06
【问题描述】:

在下面的代码中,我希望读取一个文本文件,其中每行填充数字 1-5。我希望它扫描该行并读取其中一个值并查看其是否

//This is the part of the program that will read from a text file named "file"
//To see what numbers were selected last time so the recipe for week two can be
//a completely new recipe group of 5
f, err := os.Open("file")
if err != nil {
    fmt.Println(err)
}
for {
    var z int
    var n int
    n, err = fmt.Fscanln(f, &z)
    if n == 0 || err != nil {
        break
    }
    fmt.Println("int z :", z)
}

【问题讨论】:

    标签: algorithm go


    【解决方案1】:

    您的代码在我的测试中运行良好。文件的格式可能略有不同或位于不同的位置?

    for {
        var z int
        var n int
        n, err = fmt.Fscan(f, &z)
        if n == 0 || err != nil {
            break
        }
        fmt.Println("int z :", z)
    }
    

    真的,这个问题的一个变体: Reading an integer from standard input in Golang

    【讨论】:

    • 确保文件显示 1 2 3 4 5
    • @Tbalz,你使用的是fmt.Fscanln,它一次读取整行,他使用的是fmt.Fscan
    • 啊,我明白了!
    猜你喜欢
    • 2016-07-07
    • 2018-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多