Home > Backend Development > Golang > Command line parameters in Golang program are not correctly accepted as parameters

Command line parameters in Golang program are not correctly accepted as parameters

王林
Release: 2024-02-09 09:09:13
forward
903 people have browsed it

Golang 程序中命令行参数未正确接受作为参数

#php editor Baicao sometimes encounters the problem that command line parameters are not correctly accepted as parameters when developing Golang programs. This issue may cause the program to not run properly or to obtain correct input data. In order to solve this problem, we need to carefully check the command line parameter processing part of the program to ensure that the parameters are received correctly and used correctly in the program. This article will introduce some common error causes and solutions to help developers better handle command line parameters.

Question content

I am new to golang and following an online tutorial on making a simple quiz application using command line terminal. However, when I run the code on my machine, after the first question, the remaining questions come in pairs, and it no longer accepts my answer for each question.

Screenshot example:

The process of the program is very simple -

  1. Issue getting input from local csv file
  2. Print each question and accept user-entered answers
  3. Maintain a count of correct answers and display them at the end.

csv file is also very short -

70+22,92
63+67,130
91+72,163
74+61,135
81+6,87
Copy after login

This is the complete program -

package main

import (
    "encoding/csv"
    "flag"
    "fmt"
    "os"
    "time"
)

func main() {
    // 1. input the name of the file
    fName := flag.String("f", "quiz.csv", "path of csv file")
    // 2. set the duration of timer
    timer := flag.Int("t", 30, "timer for the quiz")
    flag.Parse()
    // 3. pull the problems from the file  (calling our problem puller)
    problems, err := problemPuller(*fName)
    // 4. handle the error
    if err != nil {
        exit(fmt.Sprintf("something went wrong: %s", err.Error()))
    }
    // 5. create a variable to count our correct answers
    correctAns := 0
    // 6. using the duration of the timer, we want to initialize the timer
    tObj := time.NewTimer(time.Duration(*timer) * time.Second)
    ansC := make(chan string)
    // 7. loop through the problems, print the questions, we'll accept the answers
    problemLoop: 
        for i, p := range problems {
            var answer string
            fmt.Printf("Problem %d: %s =", i+1, p.question)

            go func() {
                fmt.Scanf("%s", &answer)
                ansC <- answer
            }()
            select {
                case <- tObj.C:
                    fmt.Println()
                    break problemLoop
                case iAns := <- ansC:
                    if iAns == p.answer {
                        correctAns++
                    }
                    if i == len(problems)-1 {
                        close(ansC)
                    }
            }
        }
    // 8. calculate and print out the result
    fmt.Printf("Your result is %d out of %d\n", correctAns, len(problems))
    fmt.Printf("Press enter to exit")
    <- ansC
}

func problemPuller(fileName string) ([]problem, error) {
    // read all the problems from the quiz.csv

    // 1. open the file
    if fObj, err := os.Open(fileName); err == nil {
        // 2. we will create new reader
        csvR := csv.NewReader(fObj)
        // 3. it will need to read the file
        if cLines, err := csvR.ReadAll(); err == nil {
            // 4. call the parseProblem function
            return parseProblem(cLines), nil
        } else {
            return nil, fmt.Errorf("error in reading data in csv from %s file; %s", fileName, err.Error())
        }
    } else {
            return nil, fmt.Errorf("error in opening the file %s file; %s", fileName, err.Error())
    }
}

func parseProblem(lines [][]string) []problem {
    // go over the lines and parse them based on the problem struct
    r := make([] problem, len(lines))
    for i := 0; i < len(lines); i++ {
        r[i] = problem {
            question: lines[i][0],
            answer: lines[i][1],
        }
    }
    return r
}

type problem struct {
    question string
    answer   string
}

func exit(msg string) {
    fmt.Println(msg)
    os.Exit(1)
}
Copy after login

I tried every line of code but can't solve it. Can someone point out what I'm doing wrong?

Workaround

I can reproduce the issue on windows (running in Command Prompt). But on linux there is no problem.

The following changes will resolve the issue:

go func() {
-   fmt.Scanf("%s", &answer)
+   fmt.Scanln(&answer)
    ansC <- answer
  }()
Copy after login

This is a known issue, reported as fmt: scanf works differently on windows and linux #23562. There is also a pending fix. Unfortunately, cl has unresolved comments and has been blocked for a long time.

The above is the detailed content of Command line parameters in Golang program are not correctly accepted as parameters. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template