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)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵
  • ¥15 cfx离心泵非稳态计算