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
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)
}
}