我是Golang的新手,在网上学习了一个关于使用命令行终端制作一个简单的测验应用程序的教程.然而,当我在我的机器上运行代码时,在第一个问题之后,其余的问题成对出现,它不再接受我对每个问题的回答.

示例屏幕截图:

program output on vscode terminal

程序的流程非常简单--

  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(在Command Prompt中运行)上重现该问题.但在Linux上没有问题.

以下更改将解决该问题:

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

这是一个报告为fmt: Scanf works differently on Windows and Linux #23562的已知问题.而且它也有pending fix分.不幸的是,CL有未解决的 comments ,并被屏蔽了很长一段时间.

Go相关问答推荐

Go:嵌入类型不能是类型参数""

如何在使用中介资源时处理函数中的`defer`

如何使用工作区方法扩展克隆的Golang库

使用Digitorus/pdfsign在GO(Golang)中签署pdf文件

使用Golang的Lambda自定义al2运行时,初始化阶段超时

无法在32位计算机上运行Golang应用程序

切片的下限和上限

Json.Unmarshal() 和 gin.BindJson() 之间的区别

Golang Docker Selenium Chrome

xml.Unmarshal 不支持的类型 struct

由于 main.go 文件中的本地包导入导致构建 docker 容器时出错

AddE 上的 Apache Tinkerpop gremlin-go 驱动程序 Next() 返回E0903:没有剩余结果

Golang invopop jsonschema 使用 if/then/else

使用 AppID 在 Windows 中启动应用程序并获取 pid

将 []float64 像素切片转换为图像

为什么我不能使用来自 gocloak 中 Login() 的访问令牌在 KeyCloak 中创建新客户端?

如何在循环中旋转图像以便在 golang 中创建 GIF?

go 堆栈跟踪:在某些函数调用参数或返回值之后的问题(?)标记是什么意思?

如何在golang中使用ozzo验证进行时间最大验证

正则表达式处理数字签名的多个条目