搜尋
首頁後端開發GolangGolang 程式中命令列參數未正確接受為參數

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。如有侵權,請聯絡admin@php.cn刪除
Golang行動:現實世界中的示例和應用程序Golang行動:現實世界中的示例和應用程序Apr 12, 2025 am 12:11 AM

Golang在实际应用中表现出色,以简洁、高效和并发性著称。1)通过Goroutines和Channels实现并发编程,2)利用接口和多态编写灵活代码,3)使用net/http包简化网络编程,4)构建高效并发爬虫,5)通过工具和最佳实践进行调试和优化。

Golang:Go編程語言解釋了Golang:Go編程語言解釋了Apr 10, 2025 am 11:18 AM

Go語言的核心特性包括垃圾回收、靜態鏈接和並發支持。 1.Go語言的並發模型通過goroutine和channel實現高效並發編程。 2.接口和多態性通過實現接口方法,使得不同類型可以統一處理。 3.基本用法展示了函數定義和調用的高效性。 4.高級用法中,切片提供了動態調整大小的強大功能。 5.常見錯誤如競態條件可以通過gotest-race檢測並解決。 6.性能優化通過sync.Pool重用對象,減少垃圾回收壓力。

Golang的目的:建立高效且可擴展的系統Golang的目的:建立高效且可擴展的系統Apr 09, 2025 pm 05:17 PM

Go語言在構建高效且可擴展的系統中表現出色,其優勢包括:1.高性能:編譯成機器碼,運行速度快;2.並發編程:通過goroutines和channels簡化多任務處理;3.簡潔性:語法簡潔,降低學習和維護成本;4.跨平台:支持跨平台編譯,方便部署。

SQL排序中ORDER BY語句結果為何有時看似隨機?SQL排序中ORDER BY語句結果為何有時看似隨機?Apr 02, 2025 pm 05:24 PM

關於SQL查詢結果排序的疑惑學習SQL的過程中,常常會遇到一些令人困惑的問題。最近,筆者在閱讀《MICK-SQL基礎�...

技術棧收斂是否僅僅是技術棧選型的過程?技術棧收斂是否僅僅是技術棧選型的過程?Apr 02, 2025 pm 05:21 PM

技術棧收斂與技術選型的關係在軟件開發中,技術棧的選擇和管理是一個非常關鍵的問題。最近,有讀者提出了...

如何在Go語言中使用反射對比並處理三個結構體的差異?如何在Go語言中使用反射對比並處理三個結構體的差異?Apr 02, 2025 pm 05:15 PM

Go語言中如何對比並處理三個結構體在Go語言編程中,有時需要對比兩個結構體的差異,並將這些差異應用到第�...

在Go語言中如何查看全局安裝的包?在Go語言中如何查看全局安裝的包?Apr 02, 2025 pm 05:12 PM

在Go語言中如何查看全局安裝的包?在使用Go語言開發過程中,經常會使用go...

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。