Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Trying to Set a Timer For Individual Question #136

Open
Pranay-ai opened this issue Nov 12, 2024 · 0 comments
Open

Trying to Set a Timer For Individual Question #136

Pranay-ai opened this issue Nov 12, 2024 · 0 comments

Comments

@Pranay-ai
Copy link

package main

import (
"encoding/csv"
"flag"
"fmt"
"os"
"time"
)

func main() {
// Parse CSV file name from command-line arguments
csvFileName := flag.String("csv", "problems.csv", "a csv file in the format of 'question,answer'")
flag.Parse()

// Open the CSV file
file, err := os.Open(*csvFileName)
if err != nil {
	fmt.Println("Failed to open the CSV file:", *csvFileName)
	os.Exit(1)
}
defer file.Close()

// Read the CSV file
r := csv.NewReader(file)
lines, err := r.ReadAll()
if err != nil {
	fmt.Println("Failed to parse the provided CSV file.")
	os.Exit(1)
}
problems := parseLines(lines)

correctAnswerCount := 0
timeLimit := 5 * time.Second

for i, p := range problems {
	fmt.Printf("Problem %d: %s = \n", i+1, p.question)

	// Create a timer for the current question
	timer := time.NewTimer(timeLimit)

	// Create a channel for the answer
	answerChannel := make(chan string)

	// Launch a goroutine to read user input
	go func() {
		var answer string
		fmt.Scanln(&answer)
		answerChannel <- answer
	}()

	select {
	case <-timer.C:
		fmt.Println("Time's up! Moving to the next question.")
	case answer := <-answerChannel:
		if answer == p.answer {
			correctAnswerCount++
		}
		timer.Stop() // Stop the timer when answer is received
	}
}

// Print the final score
fmt.Printf("You scored %d out of %d\n", correctAnswerCount, len(problems))

}

// Problem struct for each question-answer pair
type problem struct {
question string
answer string
}

// parseLines parses lines from CSV to a slice of problem structs
func parseLines(lines [][]string) []problem {
ret := make([]problem, len(lines))
for i, line := range lines {
ret[i] = problem{
question: line[0],
answer: line[1],
}
}
return ret
}

I Have been trying to Set a timer For Each Individual Question But Problem is When the Timer is expired the old "Scanln" function is still waiting for the input, Is their any way we can solve this issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant