golang和程序设计的新手。我目前正在为学习任务编写一个小型测验程序,但遇到了本教程无法解决的问题,因为我具有本教程未包含的功能。
[下面包含代码
:func runQuestions(randomize bool) int { tempqSlice := qSlice //Create temporary set of questions (Don't touch original) if randomize { //If user has chosen to randomize the question order tempqSlice = shuffle(tempqSlice) //Randomize } var runningscore int userinputchan := make(chan string) //Create return channel for user input go getInput(userinputchan) //Constantly wait for user input for num, question := range tempqSlice { //Iterate over each question fmt.Printf("Question %v:\t%v\n\t", num+1, question.GetQuestion()) select { case <-time.After(5 * time.Second): // fmt.Println("-time up! next question-") continue case input := <-userinputchan: if question.GetAnswer() == input { //If the answer is correct runningscore++ continue //Continue to next question } } } return runningscore
}
func getInput(returnchan chan<- string) { for { reader := bufio.NewReader(os.Stdin) //Create reader input, _ := reader.ReadString('\n') //Read from returnchan <- strings.TrimSpace(input) //Trim the input and send it }
}
因为问题的说明要求每个问题都有一个时限,所以我设置了一个“无穷循环循环例程”,该例程等待用户输入,然后在给出提示时将其发送。我的问题很简单:测验结束后,我想停止读者寻找输入,但是由于'reader.ReadString('/ n')'已经在等待输入,因此我不确定如何输入。
golang和程序设计的新手。我目前正在为学习任务编写一个小型测验程序,但遇到了本教程无法解决的问题,因为我没有......>
您不能立即执行此操作,但是可以通过从stdin
逐个字符地读取字符,缓冲输入并仅在用户单击Enter
时发送缓冲的数据来进行解决。
[遗憾的是,没有用于逐个字符读取的标准程序包,我将使用github.com/eiannone/keyboard
。 (您可以通过go get -u github.com/eiannone/keyboard
来获得它。)>
以下课程将是您的输入系统。您可以通过调用NewInput(yourResultChannel)
实例化它。这将从stdin
字符开始逐个读取,并将其缓冲到buf
中。一旦击中Enter
(char == 0
),它将缓冲区的内容发送到resultChannel端以重置缓冲区。