首頁  >  文章  >  後端開發  >  Golang 程式中命令列參數未正確接受為參數

Golang 程式中命令列參數未正確接受為參數

王林
王林轉載
2024-02-09 09:09:13821瀏覽

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

php小編百草在Golang程式開發中,有時會遇到命令列參數未正確接受作為參數的問題。這個問題可能導致程式無法正常運作或無法取得正確的輸入資料。為了解決這個問題,我們需要仔細檢查程式中的命令列參數處理部分,確保參數被正確接收並在程式中正確使用。本文將介紹一些常見的錯誤原因和解決方法,幫助開發者更好地處理命令列參數。

問題內容

我是 golang 新手,正在學習有關使用命令列終端製作簡單測驗應用程式的線上教學課程。然而,當我在我的機器上運行程式碼時,在第一個問題之後,其餘的問題成對出現,並且它不再接受我對每個問題的答案。

螢幕截圖範例:

程式的流程非常簡單 -

  1. 從本機 csv 檔案取得輸入問題
  2. 列印每個問題並接受使用者輸入的答案
  3. 維護正確答案的計數並在最後顯示它們。

csv 檔案也很短 -

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

這是完整的程式 -

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

我嘗試過每一行程式碼,但無法解決它。有人可以指出我做錯了什麼嗎?

解決方法

我可以在 windows 上重現該問題(在 命令提示字元 中執行)。但在 linux 上沒有問題。

以下更改將解決該問題:

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

這是一個已知問題,報告為fmt:scanf 在 windows 和 linux 上的工作方式不同#23562.並且還有一個待修復。不幸的是,cl 有未解決的評論,並且被屏蔽了很長時間。

以上是Golang 程式中命令列參數未正確接受為參數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除