


#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 -
- Issue getting input from local csv file
- Print each question and accept user-entered answers
- 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
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) }
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 }()
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!

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

This article demonstrates creating mocks and stubs in Go for unit testing. It emphasizes using interfaces, provides examples of mock implementations, and discusses best practices like keeping mocks focused and using assertion libraries. The articl

This article explores Go's custom type constraints for generics. It details how interfaces define minimum type requirements for generic functions, improving type safety and code reusability. The article also discusses limitations and best practices

The article discusses Go's reflect package, used for runtime manipulation of code, beneficial for serialization, generic programming, and more. It warns of performance costs like slower execution and higher memory use, advising judicious use and best

This article explores using tracing tools to analyze Go application execution flow. It discusses manual and automatic instrumentation techniques, comparing tools like Jaeger, Zipkin, and OpenTelemetry, and highlighting effective data visualization

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a

The article discusses managing Go module dependencies via go.mod, covering specification, updates, and conflict resolution. It emphasizes best practices like semantic versioning and regular updates.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools
