


Command line parameters in Golang program are not correctly accepted as parameters
#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!

Gohandlesinterfacesandtypeassertionseffectively,enhancingcodeflexibilityandrobustness.1)Typeassertionsallowruntimetypechecking,asseenwiththeShapeinterfaceandCircletype.2)Typeswitcheshandlemultipletypesefficiently,usefulforvariousshapesimplementingthe

Go language error handling becomes more flexible and readable through errors.Is and errors.As functions. 1.errors.Is is used to check whether the error is the same as the specified error and is suitable for the processing of the error chain. 2.errors.As can not only check the error type, but also convert the error to a specific type, which is convenient for extracting error information. Using these functions can simplify error handling logic, but pay attention to the correct delivery of error chains and avoid excessive dependence to prevent code complexity.

TomakeGoapplicationsrunfasterandmoreefficiently,useprofilingtools,leverageconcurrency,andmanagememoryeffectively.1)UsepprofforCPUandmemoryprofilingtoidentifybottlenecks.2)Utilizegoroutinesandchannelstoparallelizetasksandimproveperformance.3)Implement

Go'sfutureisbrightwithtrendslikeimprovedtooling,generics,cloud-nativeadoption,performanceenhancements,andWebAssemblyintegration,butchallengesincludemaintainingsimplicityandimprovingerrorhandling.

GoroutinesarefunctionsormethodsthatrunconcurrentlyinGo,enablingefficientandlightweightconcurrency.1)TheyaremanagedbyGo'sruntimeusingmultiplexing,allowingthousandstorunonfewerOSthreads.2)Goroutinesimproveperformancethrougheasytaskparallelizationandeff

ThepurposeoftheinitfunctioninGoistoinitializevariables,setupconfigurations,orperformnecessarysetupbeforethemainfunctionexecutes.Useinitby:1)Placingitinyourcodetorunautomaticallybeforemain,2)Keepingitshortandfocusedonsimpletasks,3)Consideringusingexpl

Gointerfacesaremethodsignaturesetsthattypesmustimplement,enablingpolymorphismwithoutinheritanceforcleaner,modularcode.Theyareimplicitlysatisfied,usefulforflexibleAPIsanddecoupling,butrequirecarefulusetoavoidruntimeerrorsandmaintaintypesafety.

Use the recover() function in Go to recover from panic. The specific methods are: 1) Use recover() to capture panic in the defer function to avoid program crashes; 2) Record detailed error information for debugging; 3) Decide whether to resume program execution based on the specific situation; 4) Use with caution to avoid affecting performance.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver CS6
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version
Useful JavaScript development tools
