doudiaozhi6658 2018-07-14 20:30
浏览 155
已采纳

如何在golang中的txt文件中编写循环的输出

i'm new in go, i want to know, how to write the output of loop for in txt file in golang here my code

package main

import (
    "fmt"
    "log"
    "os"
)

func main() {

    for i := 1; i <= 10; i++ {
        if i%2 == 0 {
            continue
        }
        fmt.Printf("%d ", i)
        file, err := os.Create("result.txt")
        if err != nil {
            log.Fatal("Cannot create file", err)
        }
        defer file.Close()

        fmt.Fprintf(file, " x equal to %d", i)

    }

}

but i get 9 instead of 1 3 5 7 9 so how to fix that

  • 写回答

1条回答 默认 最新

  • dongyu4863 2018-07-14 20:46
    关注

    The problem is that you are recreating the file each iteration of the loop, which is why the only value in the file is the last value you write in the loop.

    Try the following

    package main
    
    import (
        "fmt"
        "log"
        "os"
    )
    
    func main() {
        file, err := os.Create("result.txt")
        if err != nil {
            log.Fatal("Cannot create file", err)
        }
        defer file.Close()
    
        for i := 1; i <= 10; i++ {
            if i%2 == 0 {
                continue
            }
            fmt.Printf("%d ", i)
            fmt.Fprintf(file, " x equal to %d", i)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 使用matlab将观测点聚合成多条目标轨迹
  • ¥15 Workbench中材料库无法更新,如何解决?
  • ¥20 如何推断此服务器配置
  • ¥15 关于github的项目怎么在pycharm上面运行
  • ¥15 内存地址视频流转RTMP
  • ¥100 有偿,谁有移远的EC200S固件和最新的Qflsh工具。
  • ¥15 有没有整苹果智能分拣线上图像数据
  • ¥20 有没有人会这个东西的
  • ¥15 cfx考虑调整“enforce system memory limit”参数的设置
  • ¥30 航迹分离,航迹增强,误差分析