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 用verilog实现tanh函数和softplus函数
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题