Home  >  Article  >  Backend Development  >  My program in Golang prints the first input in a file twice

My program in Golang prints the first input in a file twice

王林
王林forward
2024-02-10 10:03:09581browse

我在 Golang 中的程序在文件中打印第一个输入两次

php Editor Xigua encountered an interesting problem when writing a program in Golang: how to print the first input twice in the file. This question seems simple, but it actually involves multiple aspects of knowledge such as how to read input, process strings, and file operations. Through in-depth research and practice, I successfully solved this problem and shared the solution with everyone. Next, I will introduce in detail the steps of my program implementation in Golang.

Question content

I try to get some csv formatted string as input and then print it to an actual csv file. It works, but it prints the first string twice.

My code looks like this:

func main() {
    scanner := bufio.newscanner(os.stdin)
    n := 0
    inputfile, err := os.create("input.csv") //create the input.csv file
    if err != nil {
        log.fatal(err)
    }

    csvwriter := csv.newwriter(inputfile)

    fmt.println("how many records ?")
    fmt.scanln(&n)
    fmt.println("enter the records")
    var lines [][]string
    for i := 0; i < n; i++ {
        scanner.scan()
        text := scanner.text()
        lines = append(lines, []string{text})
        err := csvwriter.writeall(lines)
        if err != nil {
            return
        }
    }
    csvwriter.flush()
    inputfile.close()
}

For n=2 and records:

abcd, efgh, ijklmn
opq, rstu, vwxyz

The output looks like this:

"abcd, efgh, ijklmn"
"abcd, efgh, ijklmn"
"opq, rstu, vwxyz"

This is my first time using golang and I'm a bit lost :d

Solution

You are writing the csv in a loop so that the first line prints double. Here is the corrected code.

package main

import (
    "bufio"
    "encoding/csv"
    "fmt"
    "log"
    "os"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    n := 0
    inputFile, err := os.Create("input.csv") //create the input.csv file
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        inputFile.Close()
    }()

    csvwriter := csv.NewWriter(inputFile)
    defer func() {
        csvwriter.Flush()
    }()
    fmt.Println("How many records ?")
    fmt.Scanln(&n)
    fmt.Println("Enter the records")
    var lines [][]string
    for i := 0; i < n; i++ {
        scanner.Scan()
        text := scanner.Text()
        lines = append(lines, []string{text})

    }
    err = csvwriter.WriteAll(lines)
    if err != nil {
        return
    }
}

The above is the detailed content of My program in Golang prints the first input in a file twice. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete