golang 和一般编程新手。我目前正在为学习任务编写一个小测验程序,但遇到了教程 Unresolved 问题,因为我有教程中未包含的功能。
代码如下:
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
}
}
因为问题的规范要求每个问题都有时间限制,所以我设置了一个“无尽的 for loop goroutine”运行,等待用户输入,然后在给出时发送。我的问题很简单:我想在测验结束后停止读者寻找输入,但由于'reader.ReadString('/n')' 已经在等待输入,我不知道如何。
最佳答案
I would like to stop the reader looking for input once the quiz is over
当读者在寻找输入时,您可以使用在其后台运行的 goroutine 来检查测验计时器是否已过期。
假设您的测验计时器是 30 秒。将计时器传递给 goroutine
getInput
并检查计时器是否到期。var runningscore int
userinputchan := make(chan string) //Create return channel for user input
myTime := flag.Int("timer", 30, "time to complete the quiz")
timer := startTimer(myTime)
go getInput(userinputchan, timer)
func startTimer(myTime *int) *time.Timer {
return time.NewTimer(time.Duration(*myTime) * time.Second)
}
func getInput(returnchan chan<- string, timer *time.Timer) {
for {
reader := bufio.NewReader(os.Stdin) //Create reader
go checkTime(timer)
input, _ := reader.ReadString('\n') //Read from
returnchan <- strings.TrimSpace(input) //Trim the input and send it
}
}
func checkTime(timer *time.Timer) {
<-timer.C
fmt.Println("\nYour quiz is over!!!")
// print the final score
os.Exit(1)
}
关于go - 停止使用 'bufio.NewReader(os.Stdin)' 查找用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61873357/